[javascript] Why can't I change my input value in React even with the onChange listener

I am quite new to React and after going through some tutorials, I was trying the below code of mine.

I made one component, passed props to it from a store, on componentWillMount I make a new state for component. Rendering is fine till now.

Next I bound my state to value of an input box and I have onChange listener as well. Still, I can't change my values in the field.

Since, I am from Angular background, I am assuming binding input's value to state like below will automatically update the property name in state object. Am I wrong here?

componentWillMount(){
    this.setState({
        updatable : false,
        name : this.props.name,
        status : this.props.status
    });
}

//relevant DOM from component's render function
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange.bind(this)}/>

onTodoChange(){
    console.log(this);
    //consoling 'this' here, shows old values only.
    //not sure how and even if I need to update state here.
    // Do I need to pass new state to this function from DOM
    //TODO: send new data to store
}

My onTodoChange function console the value of this which has same value of state as while initializing. How do I go about changing state by typing in input boxes, so that I can send them to the stores?

This question is related to javascript reactjs state onchange

The answer is


You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:

<input type="text" onChange={e => this.setState({ text: e.target.value })}/>

In react, state will not change until you do it by using this.setState({});. That is why your console message showing old values.


I think it is best way for you.

You should add this: this.onTodoChange = this.onTodoChange.bind(this).

And your function has event param(e), and get value:

componentWillMount(){
        this.setState({
            updatable : false,
            name : this.props.name,
            status : this.props.status
        });
    this.onTodoChange = this.onTodoChange.bind(this)
    }
    
    
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>

onTodoChange(e){
         const {name, value} = e.target;
        this.setState({[name]: value});
   
}

In React, the component will re-render (or update) only if the state or the prop changes.

In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.

onTodoChange(event) {
        // update the state
    this.setState({name: event.target.value});
}

If you would like to handle multiple inputs with one handler take a look at my approach where I'm using computed property to get value of the input based on it's name.

import React, { useState } from "react";
import "./style.css";

export default function App() {
  const [state, setState] = useState({
    name: "John Doe",
    email: "[email protected]"
  });

  const handleChange = e => {
    setState({
      [e.target.name]: e.target.value
    });
  };

  return (
    <div>
      <input
        type="text"
        className="name"
        name="name"
        value={state.name}
        onChange={handleChange}
      />

      <input
        type="text"
        className="email"
        name="email"
        value={state.email}
        onChange={handleChange}
      />
    </div>
  );
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to state

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter? Updating an object with setState in React Why can't I change my input value in React even with the onChange listener React setState not updating state How to use onClick with divs in React.js React - how to pass state to another component React.js, wait for setState to finish before triggering a function? setInterval in a React app React: how to update state.item[1] in state using setState? AngularJS ui router passing data between states without URL

Examples related to onchange

Why can't I change my input value in React even with the onChange listener React Checkbox not sending onChange Set Label Text with JQuery android on Text Change Listener Jquery select change not firing onchange event on input type=range is not triggering in firefox while dragging select2 onchange event only works once Dropdown using javascript onchange How to fire a change event on a HTMLSelectElement if the new value is the same as the old? jQuery - on change input text