Imagine that we host an IT conference and want to make a list of guests. Obviously, we want to collect their first name and last name. Additionally, we can ask for their work experience, but that information is not required. Let's prepare a form for the guests, so they can sign up for our event, by using uniforms!
1. Install the required packages
To start using uniforms, we have to install three independent packages:
In this example, we will use the JSONSchema to describe our desired data format and style our form using Semantic UI theme.
Note: When using a themed package, remember to include correct styles! If you are willing to run this example by yourself, have a read on Semantic UI React's theme usage.
2. Start by defining a schema
After we've installed required packages, it's time to define our Guest schema. We can do it in a plain JSON, which is a valid JSONSchema instance:
As you can see, we've defined three properties -
lastName, that are of string type, and
which is an integer, with a value between 0 and 100.
3. Then create the bridge
Now that we have the schema, we can create the uniforms bridge of it, by using the corresponding uniforms schema-to-bridge package.
Creating the bridge instance is necessary - without it, uniforms would not be able to process form generation and validation.
As we are using the JSONSchema, we have to import the
Now you may think that we can simply do:
However, there's small caveat with using the JSONSchemaBridge.
Because of its simplicity, JSONSchema doesn't provide any validation checkers, so in order to properly validate our submitted data,
we need to manually define a validator, and that is required by the uniforms
To manually create the validator, we will use the ajv package:
Now that we have both the schema and the validator, we can create the uniforms bridge:
Just to recap, the whole
GuestSchema.js file looks like this:
4. Finally, use it in a form!
uniforms theme packages provide the
AutoForm component, which is able to generate the form based on the given schema.
All we have to do now is to pass the previously created GuestSchema to the
And that's it!
AutoForm will generate a complete form with labeled fields, errors list (if any) and a submit button.
Also, it will take care of validation and handle model changes.