Skip to content

Instantly share code, notes, and snippets.

@uicoded
Created October 30, 2020 14:26
Show Gist options
  • Save uicoded/d6205eba8a5c5d86c4228fb64234c3c7 to your computer and use it in GitHub Desktop.
Save uicoded/d6205eba8a5c5d86c4228fb64234c3c7 to your computer and use it in GitHub Desktop.
React Controlled Components (Class Syntax)
<h1>React Controlled Components (Class Syntax)</h1>
<div id="root"></div>
<p>Submit the form</p>
<p><a href="https://reactjs.org/docs/forms.html#controlled-components">Controlled Components - React Docs</a></p>
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
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} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment