In ReactJS, handling form input is similar to handling input in other HTML-based forms, but with a few key differences. Here are the basics of form handling in ReactJS:
- Form Element: First, define a
<form>
element in your component’s render method, and specify aonSubmit
handler to handle form submissions. - Form Input Elements: Add form input elements, such as
<input>
,<textarea>
, and<select>
, to your form. Each input element should have avalue
attribute that reflects the current state of the input. - State Management: Define state variables to keep track of the current value of each input element. In React, form input elements are “controlled components”, which means that their values are controlled by state. When the user interacts with an input element, update the corresponding state variable.
- Event Handling: Use the
onChange
event to update the state variables when the user types into an input element. You can also use other events, such asonBlur
, to handle input events as needed. - Submit Handling: In your
onSubmit
handler, prevent the default form submission behavior by callingevent.preventDefault()
. Then, use the current state values to perform any necessary actions, such as sending the data to a server.
Here’s an example of how to handle a simple form in ReactJS:
class MyForm extends React.Component { constructor(props) { super(props); this.state = { name: '', email: '', message: '', }; } handleInputChange = event => { const target = event.target; const name = target.name; const value = target.value; this.setState({ [name]: value, }); } handleSubmit = event => { event.preventDefault(); // Do something with the form data } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} /> </label> <label> Email: <input type="email" name="email" value={this.state.email} onChange={this.handleInputChange} /> </label> <label> Message: <textarea name="message" value={this.state.message} onChange={this.handleInputChange} /> </label> <button type="submit">Submit</button> </form> ); } }
In this example, the form has three input elements: a text input for the name, an email input for the email address, and a textarea for the message. Each input element has a value
attribute that reflects the current state value, and an onChange
handler that updates the state when the user types. The handleSubmit
method is called when the user submits the form, and can be used to send the data to a server or perform other actions as needed.