Build forms with React in 2 minutes

An important react pattern we haven't talked about yet, our so called controlled inputs. Controlled inputs are how you build input fields in React so that the actually value is controlled by state.

Imagine you have an input with a value in state. Whenever you press a button, you update your value and that value then adds a letter here. And that's the best way you can always keep your app state and your rendered stated in sync, so that you can build a normal data API that uses your fields without having to read state directly from the HTML.

I prepare the simple form component for us that has an input field for a name and a text area. To wire that up, we're going to create a state, a username and a text to render those here. Value as username text area has text. We take both of those from state. When changing our input on change username, update states saying username is event.target.value. And when I'm typing, you can see the username updating. So now we always have the value of our username in state, and it's also being rendered into our text.

You can do something similar with the text area I think. Target.value. It does seem to work. And we can make it multi ... let's make all of this submittable. We're gonna add an unsubmit to our form. Take an event, which we're going to ignore. Event, prevent the fault. This is going to stop it from the default behavior of reloading our page. This [inaudible 00:01:36].submit our state. And now this is just a very simple API where we know that we want to provide the same value to our submit function as we have in state. And if we press submit, adds a new message the our message feed.

So that's the gist of building simple forms in React. You keep your field values in state. Whenever you have a change event, you update your state and you don't really keep anything in the actual HTML itself. Usually, when you would be doing a complex form, you would use something like [redux 00:02:07] or [inaudible 00:02:08] to control just the form itself and also add error states, validations and things of that nature.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec