* fix: replace sh with shell fix replace terminal with shell fix replace node with js fix replace output with shell fix replace cs with csharp fix replace c++ with cpp fix replace c# with csharp fix replace javasctipt with js fix replace syntax with js fix replace unix with shell fix replace linux with shell fix replace java 8 with java fix replace swift4 with swift fix replace react.js with jsx fix replace javascriot with js fix replace javacsript with js fix replace c++ - with cpp fix: corrected various typos fix: replace Algorithm with nothing fix: replace xaml with xml fix: replace solidity with nothing fix: replace c++ with cpp fix: replace txt with shell fix: replace code with json and css fix: replace console with shell
1.5 KiB
title
title |
---|
Create a Controlled Form |
Create a Controlled Form
Creating a controlled form is the same process as creating a controlled input, except you need to handle a submit event.
First, create a controlled input that stores its value in state, so that there is a single source of truth.
(This is what you did in the previous challenge.) Create an input element, set its value attribute to the input variable located in state. Remember, state can be accessed by this.state
. Next, set the input element's onChange
attribute to call the function 'handleChange'.
Solution
<input value={this.state.input} onChange={this.handleChange}/>
Next, create the handleSubmit method for your component. First, because your form is submitting you will have to prevent the page from refreshing. Second, call the setState()
method, passing in an object of the different key-value pairs that you want to change. In this case, you want to set 'submit' to the value of the variable 'input' and set 'input' to an empty string.
handleSubmit(event) {
event.preventDefault();
this.setState({
input: '',
submit: this.state.input
});
}
Now that your data is being handled in state, we can use this data. Create an h1
element. Inside of your h1
element put your 'submit' variable. Remember, 'submit' is located within state so you'll need to use this.state
. Additionally, placing the variable within JSX requires curly braces { }
because it is JavaScript.
<h1>{this.state.submit}</h1>