React Bootstrap — Form State and Validation, and Input Groups

Image for post
Image for post
Photo by Nathalia Segato on Unsplash

React Bootstrap is one version of Bootstrap made for React.

It’s a set of React components that have Bootstrap styles.

In this article, we’ll look at how to add forms and input groups to a React app with React Bootstrap.

Form Libraries

We can use form libraries to make form validation easier for us.

React Bootstrap has integration with the Formik library to let us bind our input values to states.

It also does form validation when it’s used with Yup.

For instance, we can use it by writing:

We create the form validation with Yup before we create the component.

All the fields are marked required.

Then in the component, we use the Formik component to create the form.

We set the initial values with the initialValues prop.

It takes a callback that has an object with various properties that we’ll pass into our form control components.

handleSubmit is passed into the onSubmit prop of the form element.

handleChange updates the state from the input values of the form controls, so it’s passed into the onChange prop of each form control.

values is an object with the inputted values, so it’s passed in as the value of each form control.

touched indicates whether the user has interacted with the form or not.

We can use that while we check form control validity.

errors is an object with the form validations errors divided by field.

So we can also use that in the isValid prop.

Once we have that, we have a form with validation and we didn’t have to write code to set the input values of each field as a state value and check them ourselves.

Input Group

We can use the InputGroup component to lets us add content besides an input box.

For instance, we can write:

to add an InputGroup with the @ sign to the left of the input box.

InputGroup.Prepend lets us add content to the left of the input.

We can also use InputGroup.Append to add content to the right of the input.

For example, we can write:

Input Group Sizing

We can change the size of the InputGroup by using the size prop.

For example, we can write:

to make the input group extra small.

We can also make the size extra large with lg as the value.

Image for post
Image for post
Photo by niko photos on Unsplash

Conclusion

Form validation can be made easy with Formik and Yup integration.

Input groups lets us add content to the left or right of the input box.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store