Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am following this React tutorial , and I am trying to understand everything going on in the following code segment. Could someone explain what the handleChange() is doing and why it is important?

Is it for storing the inputted information so the back-end can process/store it?

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>

This is updating your state's this.state value and the same state's value used by input to show the current input value={this.state.value} by you.

Take An example Suppose that you enter "Farro" as input, every time you enter handleChange will be called and update state value As "Farro" and in input field will show "Farro".

The this.handleChange is triggered by the input element and triggers the changing of the this.state.value property which in turn changes the value of the input field. This is important because react uses states to display information in the DOM.

You could name the handleChange whatever you want just as long as it is triggered from the input field & the value updates the state.

here is some additional reading: https://reactjs.org/docs/forms.html

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.