# Goals
- Build forms with React
- Understand controlled components
## Forms
- HTML form works !== DOM form in react
- In React : function that handle submit of form,
finction that access to the user data
- [Controlled Components]
## Controlled Components
- In HTML, form elements maintain their own state and update it when user types
- In React, mutable state is kept in the state of components, and only update with setState()
- How can we control form input state in React?
- React controls : What is shown (the value of the component)
What happen when user types ('this' gets kept in state)
-> [Controlled Components]
## How the controlled form works
- handleChange(){
// handle every keystroke
this.setState({
fullName: evt.target.value
});
}
import React, { Component } from 'react';
class Form extends Component {
constructor(props) {
super(props);
this.state = { username: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(evt) {
this.setState({ username: evt.target.value });
}
handleSubmit(evt) {
evt.preventDefault(); //prevent refreshing
alert(`You typed ${this.state.username}`);
this.setState({ username: "" });
}
render() {
return (
<div>
<h1>Form</h1>
<form onSubmit={this.handleSubmit}>
<input
type="text"
value={this.state.username}
onChange={this.handleChange}
/>
<button>Submit</button>
</form>
</div>
);
}
}
export default Form;
'react' 카테고리의 다른 글
Handling multiple form : shopping list exercise (0) | 2020.06.14 |
---|---|
React events : event method binding and passing method to child (0) | 2020.06.14 |
State exercise : coin flipper (0) | 2020.06.14 |
State exercise : lottery balls (0) | 2020.06.14 |
More State : data structure and designing state (0) | 2020.06.14 |