Written by: Geoffrey Callaghan
React-jsonschema-form tutorial
React-Jsonschema-Form Tutorial
react-jsonschema-form
is a powerful library for building forms in React based on JSON schemas. It allows you to define your form structure using JSON, making it highly customizable and flexible. Here’s a step-by-step tutorial on how to use react-jsonschema-form
:
react-jsonschema-form
You can install react-jsonschema-form
via npm or yarn:
npm install @rjsf/core @rjsf/material-ui
# or
yarn add @rjsf/core @rjsf/material-ui
Define your form schema using JSON. This schema will define the structure of your form, including field types, labels, validations, etc. For example:
{
"type": "object",
"properties": {
"name": { "type": "string", "title": "Name" },
"email": { "type": "string", "title": "Email", "format": "email" }
},
"required": ["name", "email"]
}
Create a new component to render your form using react-jsonschema-form
. Here’s an example:
// FormComponent.js
import React from 'react';
import Form from '@rjsf/material-ui';
const schema = {
type: 'object',
properties: {
name: { type: 'string', title: 'Name' },
email: { type: 'string', title: 'Email', format: 'email' }
},
required: ['name', 'email']
};
const uiSchema = {
name: { 'ui:autofocus': true }
};
const FormComponent = () => {
const onSubmit = ({ formData }) => {
console.log('Form data:', formData);
};
return (
<Form
schema={schema}
uiSchema={uiSchema}
onSubmit={onSubmit}
/>
);
};
export default FormComponent;
Use your FormComponent
in your main application or wherever you need it:
// App.js
import React from 'react';
import FormComponent from './FormComponent';
const App = () => {
return (
<div>
<h1>React JSONSchema Form Example</h1>
<FormComponent />
</div>
);
};
export default App;
Run your React application and see the form in action:
npm start
react-jsonschema-form
is a powerful library for building dynamic forms in React. This tutorial covered the basic setup and usage of react-jsonschema-form
to create a simple form component. You can further customize your forms by exploring additional props, widgets, and validation options provided by the library. Check out the official documentation for more information and advanced usage.