DEV Community

loading...

React. Let's talk Forms.

Carl-Lundgren
Hello there.
・2 min read

So, I've been learning React recently and it is interesting. It is built off of JavaScript and most of it behaves like JS, with some extra bells and whistles. In this post though, we'll be talking about something that is pretty different between the two. Forms.

JavaScript Forms (well, HTML I guess)

Forms are an HTML thing that allows for users to input information. Have you ever logged into a website? That was probably using a form. JavaScript is able to interact with Forms, which shouldn't be surprising given it's HTML, but because the information that forms gives changes based on user input, you can do a bit more with it. You can use JS with Forms to, for example, make sure a password has 8 or more characters, a number, and a special character. Overall, though, Forms is still a pretty simple tool that works, more or less, like any other use of HTML in JS.

React Forms

React forms work a bit differently. They're still technically HTML elements, but they are a bit special. Before we get into that though, some context. Classes, which most files in React are, have a thing called state. State is an object that allows you to store information that can be accessed from anywhere inside the class. Now that we have some context, how does this connect to forms? Forms in React basically have their own state. This state can be accessed when you call upon the form, but there's something else special you can do with it. You can link the forms state to the state that the class has. This makes what is called a Controlled Component and it looks like this:

state = {
    value: ""
}

<input value={this.state.value} onChange={() => (this.setState({value: event.target.value}))} />
Enter fullscreen mode Exit fullscreen mode

(This is an example that leaves out some important things but gets across this broad strokes)

Controlled Components don't erase the class' state, but instead intermingle the two so the class state is the one true state. It's a simple thing, but something very useful and good to know.

While a lot of this post was working more in theory than practice, I hope that this gave you some practical knowledge that you can use down the line.

Discussion (0)