Search code examples
javascriptreactjssetstate

How to use setState and eventHandler both at a time for arrays in reactjs?


I'm new to React and I'm unable to use setState with eventHandlerMethod (event.target.value). My array is not getting modified. The same previous value is being printed everytime without changing anything.

This is my code

 class App extends Component {
  state={
    userName : ["prakash" , "Shree Harsha"]
  }

  clickChangeListener = (event) =>{
   // console.log(this.state.userName[0])
    this.setState=({ userName : [event.target.value , event.target.value]});
  }
   render(){
    return (
      <div className="App">
        <h1>Welcome to react app</h1>
        <UserInput click={this.clickChangeListener}/>
       <UserOutput  
                   name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
       <UserOutput name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
       <UserOutput name1={this.state.userName[0]} 
                   name2={this.state.userName[1]} />
      </div>
    );
  }
}

What changes should I make so that my code works?


Solution

  • Just remove the = char.

    Like the following:

    this.setState({ userName : [event.target.value , event.target.value]});
    

    setState is a function, read further here: https://reactjs.org/docs/react-component.html#setstate

    I hope that helps!