Amir Shahbabaie
Amir Shahbabaie

Reputation: 1412

change input based on props or state in react

I have a component that includes an input box. This component will receive a prop to initiate the value for input box.

class MyInput extends React.Component{
 constructor(props){
    super(props);
    this.state = {
        phrase : this.props.phrase
    }
 }
 onChange(e) {
    this.setState({
      phrase: e.target.value
    })
 } 
 render(){
   return <input value={this.state.phrase}
           onChange={this.onChange.bind(this)}/>
  }
}

Now, I want to be able to change the value of the input box by changing props as well, but since I need the input to be in sync with state I have no idea how to do it.

Upvotes: 1

Views: 1655

Answers (1)

Shanti Swarup Tunga
Shanti Swarup Tunga

Reputation: 641

class MyInput extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      phrase: props.phrase
    };
  }
  onChange = (e) => {
    this.setState({
      phrase: e.target.value
    });
  }
  componentDidUpdate(prevProps) {
    if (this.props.phrase != prevProps.phrase) {
      this.setState({ phrase: this.props.phrase });
    }
  }
  render() {
    return <input value={this.state.phrase} onChange={this.onChange} />;
  }
}

Upvotes: 2

Related Questions