anivas
anivas

Reputation: 6567

React updating state within the same component

I am new to react, I thought setting state will re-render react component. Did I miss something here, my text is not displayed until I call this.forceUpdate().

export default class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state = { value: ''};
    this.handleChange = this.handleChange.bind(this);   
  }

  render() {
    return (
        <div>
            <input type="text" onChange={this.handleChange}   />
            <p> You entered {this.state.value} </p>
        </div>
    );
  } 

  handleChange(event){      
    this.state = { value: event.target.value };     
    this.forceUpdate();
  }
}

Upvotes: 1

Views: 654

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77512

You should call .setState method instead of assign new value to this.state

handleChange(event){      
  this.setState({ value: event.target.value })
}

Upvotes: 1

Related Questions