In this tutorial, you will learn how to build a simple web form using ReactJS. The difference with this form is that the forms elements will be defined using a JSON schema in code! Over the years, I've created hundreds of forms. Creating forms is probably my least favourite task in the world. When writing the code to create a form, the majority of your effort will be in copying and pasting a lot of boilerplate code to create elements, validation, placeholder text, and labels. Anything to alleviate the pain of creating web forms is a great thing to strive for in life. This is why I recommend that you consider checking out JSON schema.

What Is JSON Schema?

As the name implies, React JSON schema form, allows you to define your form using JSON! You can pass your JSON schema into a component and your form magically builds without you having to set up the form elements yourself, sounds good right? To get started with React JSON schema form, install it via this NPM command:

Once the library is installed, you can need to define your forms schema, like so:

A form can then be defined using this code:

Running this component should result in a form that looks similar to the image below:

React JSON schema form

I know what you're thinking, beautiful right? Defining a simple form in JSON through configuration rather than code will make your life easier. In JSON schema we declare the properties for the form, in this case, a single textbox element, called name. The 'name' element is a required form element. If a user tried to submit the form without adding any text inside of it, an error will be generated. One thing to note is that the submit button is generated for us, however, it is not hooked up. Not having an event handler for the form hooked up is pretty pointless. When someone submits the form we want something to happen! This can be achieved by creating a new event handler, like this:

Hooking up the submit button is pretty straightforward. Create a normal React component. Hook up an event handler as normal, binding it within the constructor. When the form is submitted, the handler will receive an object with a key for each field in the form, simple! If you have some super custom complex form, then React JSON schema might not be the best fit. For fairly simple forms though, you must agree that defining a form in JSON is a lot less tedious than manually having to write it! More information can be found here. Happy Coding 🤘