Forms in React Flashcards
What are controlled components?
in HTML, form elements such as and typically maintain their own state and update it based on user input. In React we have our own state that is kept in components and only updated with setState(). How do we use React to control form input state? React controls what is shown(value of component) and what happens when the user types(this gets kept in state). Input elements controlled in this way are called controlled components.
When you assign an handler to the onChange event, that event itself is passed as a parameter to the handler. From this event we can extract the value of the input element using event.target.value. So anytime we change the input value, that value is captured using event.target.value.
In other words, the “value” is set to the state in react
Example Code:
this.state = {email: ‘’}
this.changeEmailHandler=(event) => {this.setState({email: event.target.value})
}
What is Computed Property Names and why is it useful?
It is a new feature introduced in ES2015. It allows us to create a regular variable and add in a property, but we use array brackets (has nothing to do with arrays), and set value to be whatever.
Example: let microchip = 1432345234; let catData = { [microchip]: "Blue Steele" }
this is helpful in reducing duplication of making multiple onChange handler for every single input, so now we can make one generic function for multiple inputs.
How do we handle multiple inputs?
Add the HTML name attribute to each JSX input element and let handler function decide the appropriate key in state to update based on event.target.name
Example: handleChange(evt) { this.setState({ [evt.target.name]: evt.target.value }); }
the way evt.target.name works is that every input on our form has to have a name that matches exactly the name we used in the state.. So if we had a state which contained username, email, password, then when we type in the username the state of that gets updated but not the others, when we type in email the state of that updates, etc.
So in the input we have our type, placeholder, value, and onChange. We also have a name and we set that in ‘’ same to what it is in the state.