Learn the fundamentals of React, including simple and class components, state, props, and submitting form data.
Controlled Text Example
<div id="root"></div> |
class NameForm extends React.Component { | |
constructor(props) { | |
super(props); | |
this.handleChange = this.handleChange.bind(this); | |
this.handleSubmit = this.handleSubmit.bind(this); | |
this.handleSexChange = this.handleSexChange.bind(this); | |
this.state = { | |
value: "", | |
sex: "male" | |
}; | |
} | |
handleChange(event) { | |
this.setState({ | |
value: event.target.value.toUpperCase() | |
}); | |
} | |
handleSexChange(event) { | |
this.setState({ | |
sex: event.target.sex | |
}); | |
} | |
handleSubmit(event) { | |
alert("A name was submitted: " + this.state.value); | |
event.preventDefault(); | |
} | |
render() { | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<label> | |
Name: | |
<input type="text" value={this.state.value} onChange={this.handleChange} /><br/> | |
<textarea value={this.state.value} onChange={this.handleChange} /><br/> | |
<select value={this.state.sex} onChange={this.handleSexChange}> | |
<option value="male">male</option> | |
<option value="female">female</option> | |
</select> | |
<br/> | |
<select multiple={true} value={["B","C"]}> | |
<option value="A">A</option> | |
<option value="B">B</option> | |
<option value="C">C</option> | |
</select> | |
<br/> | |
</label> | |
<input type="submit" value="submit" /> | |
</form> | |
); | |
} | |
} | |
ReactDOM.render( | |
<NameForm />, | |
document.getElementById("root") | |
); |
<script src="https://unpkg.com/react/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> |