Web / ReactJS Interview questions
How do you create a form in React?
React forms are identical to HTML forms. However, the state is contained in the state property of the component in React and is updateable only via the setState() method.
The elements in a React form cannot directly update their state. Their submission is handled by a JS function, which has full access to the data entered into the form by a user.
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> ); } }
More Related questions...