Initializing an input field with props value in react

Viewed 6462

I've got a child component that has a text input field whose value should be initialized with props from parent component (this.props.index).

This should be controlled input, since I want to be able to store the text of the input.

Now, if I set the value to the state's attribute, whenever the component gets re-rendered, it's never updated, since setState is never called:

<input type={"text"} placeholder={"Index"} className={"form-control"}
                       value={this.state.index} onChange={this.updateStudentIndex}/>

On the other hand, if I set the value to the prop's attribute, it's fixed and changes cannot be made:

<input type={"text"} placeholder={"Index"} className={"form-control"}
                       value={this.props.index} onChange={this.updateStudentIndex}/>

How can I both initialize the state with this.props.index, and still be able to track changes in the input's value this.state.index?

Edit: Initialization should be done in async mode, i.e. when I click a button from the parent component.

4 Answers

If you are familiar with The Component Lifecycle, use componentWillReceiveProps, and set there then new state

componentWillReceiveProps(nextProps) {
   if(this.props.index !== nextProps.index) {
     this.setState({index: nextProps.index})
   }
}

And you can hold your value in state, so on componentWillMount set your state.index to props.index

In the constructor read the value from props and set that to state, this way you will get the props.index and maintain the changes in the state afterword. In the onChange event handler you can update index with the current value.

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: props.index
    }
  }
  ...
  render() {
    const { index } = this.state;
    ...
  }
}

Hope this will help!

Related