Search code examples
reactjsreact-reduxflux

ReactJS component set state not doing anything?


I'm a newbie in ReactJS. I'm trying to do a searchbar as following:

class SearchBar extends Component {
  constructor(props) {
    super(props);

  this.state = {term: ''};
  }

  render() {
    return (
      <div>
        <input onChange={ event => this.setState({ term: event.target.value })} />
      </div>
    );
  }
}

It works but the problem is I couldn't get the changed value of the input. What's wrong with it? I couldn't find a solution. Thanks for your help.


Solution

  • You are not setting the value of the input. You need to change your input to controlled component which has its value set by state so it's value only changes when the state changes.

    <input
          value = { this.state.term }
          onChange= { (event) => this.setState({ term: event.target.value }) } />
    

    Thus, this.state causes the component to render and when it re-renders the value of the element(input-in example) is set to the new value of this.state.term.