Forms in React JS

 Forms in React JS


React makes it easy to handle form input and validation. Here's an example of a component that uses a form:

jsx


class Form extends React.Component {

  constructor(props) {

    super(props);

    this.state = { name: '', email: '' };

  }


  handleSubmit(event) {

    alert('Name: ' + this.state.name + '\nEmail: ' + this.state.email);

    event.preventDefault();

  }


  handleNameChange(event) {

    this.setState({ name: event.target.value });

  }


  handleEmailChange(event) {

    this.setState({ email: event.target.value });

  }


  render() {

    return (

      <form onSubmit={(event) => this.handleSubmit(event)}>

        <label>

          Name:

          <input type="text" value={this.state.name} onChange={(event) => this.handleNameChange(event)} />

        </label>

        <br />

        <label>

          Email:

          <input type="text" value={this.state.email} onChange={(event) => this.handleEmailChange(event)} />

        </label>

        <br />

        <button type="submit">Submit</button>

      </form>

    );

  }

}


ReactDOM.render(

  <Form />,

  document.getElementById('root')

);

In this example, the Form component has three methods:


handleSubmit: This method is called when the form is submitted. It alerts the user with the values of the input fields and prevents the default form submission behavior.

handleNameChange: This method is called when the name input field is changed. It updates the state with the new value of the input field.

handleEmailChange: This method is called when the email input field is changed. It updates the state with the new value of the input field.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...