Controlled Forms

Daniel Cooper
2 min readAug 13, 2020

--

This blog should go over how you can make a controlled form there are really only four main steps to create a controlled form. Step one is making the state to hold the value. Step two create your form. Step three pass state down to the value of your input. Step four creates your function that will change the state for you and pass that to an event handler.

Step One: Here are going to set up our state you can do this one of two ways you can use the constructor method shown at the top of the code. Or you can go with the second option which is to just use “state ={}” both of these are shown below.

class BlogCode extends Component {constructor(props) {
super(props)
this.state = { value: ''}
}
// orstate = {
userInput: ''
}

Step Two: In this step, we are just setting up a simple form that takes in a text input from the user that we will use late on. At this point in time, our form is not controlled because the value of our form is not yet determined by the state.

render() {
return (
<form>
<lable>
Pets Name:
</label>
<input type="text" placeholder="pet name here">
</form>
)
}

Step Three: So now that we have our state and we have our form let pass down that state to the form by doing this we make are making that state the single source of truth for the value. So whenever that state changes the value will change and become the same. (Any changes or addition to the code are bolded)

class BlogCode extends Component {constructor(props) {
super(props)
this.state = { userInput: ''}
}
// orstate = {
userInput: ''
}
render() {
return (
<form>
<lable>
Pets Name:
</label>
<input type="text" placeholder="pet name here" value = {this.state.userInput}
</form>
)
}

Step Four: In the last step we will be creating our function and event handler this is what will update our state and since we are going to be calling setState the page will also render. (Any changes or addition to the code are bolded)

class BlogCode extends Component {constructor(props) {
super(props)
this.state = { userInput: ''}

this.valueUpdater = this.valueUpdater.bind(this)
}
// orstate = {
userInput: ''
}
valueUpdater(event) {
this.setState({userInput: event.target.value})
}
render() {
return (
<form>
<lable>
Pets Name:
</label>
<input type="text" placeholder="pet name here" value = {this.state.userinput} onChange={ this.valueUpdater } >
</form>
)
}

That’s it you have now created a controlled form congrats. You can use this for many things like showing the value update live, search functions, filter functions, etc..

I hope this was helpful and helped you gain a better understanding of how to make a controlled form. There are tons of great articles and blogs you read that go way more in-depth if you are still looking for more information. I will link the articles and blogs I used to do my research on this topic down below.

links I used:

--

--

No responses yet