Categories
React

Managing an Input’s Value in the Parent’s State in React

Say you want to share the value of an input field with other components; how do you do that?

It’s actually really straightforward, however it’s something I find myself researching again and again every time I need to do it.

This is a simple example.

In the parent component, you need a number of things:

  1. Setup your state with a property for your input field’s value
  2. Bind the handleChange class method to this
  3. Your handleChange method to update the state when it’s called
  4. Pass as a prop the state property
  5. Pass as a prop the handleChange method
// Parent component

import...

class Parent extends React.Component {

  constructor(props) {
    super(props);
    this.state = { inputValue: "" }; // 1
    this.handleChange = this.handleChange.bind(this); // 2
  }

  handleChange(event) { // 3
    this.setState({ inputValue: event.target.value });
  }

  render() {
    return (
      <div>
        <Child
          inputValue={this.state.inputValue} // 4
          handleChange={this.handleChange} // 5
        ></Child>

      </div>
    );
  }
}

export default Parent;

And in the child, all we need is to utilise the two props that were passed to it:

  1. Set the <input>‘s value attribute to the value set in the parent’s state
  2. Call the parent’s handleChange method via the onChange event when a user edits the input field
// Child component

function Child(props) {
  return (
    <div>
      <input type="text" value={props.inputValue} onChange={props.handleChange} />
    </div>
  );
}

export default Child;

It’s all very logical in the sense that the Child component becomes focused purely on it’s function as an input field; it displays a value, receives a new value and passes that new value to its parent. That’s about it.

The Parent component does all the heavy lifting here in terms of managing the state. In terms of scaling this approach, we’ll want to avoid bloating or otherwise over-complicating the Parent component with more logic so being able to re-use the same handleChange method between different child components would be beneficial (i.e. by passing the state property that you want to change as an argument to the method).

Leave a Reply

Your email address will not be published. Required fields are marked *