Solution 1 :

you can refactor your input to each have a local state to handle its input value. at componentDidUpdate you check if this.props.val is a new value:

Input.js

import React, { Component } from "react";

export default class Input1 extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      inputValue: ''
    };
  }

  handleKeyPress = e => {
    if (e.keyCode === 13) {
      this.inputRef.current.blur();
    }
  };

  handleBlur = e => {
    this.props.setVal(this.state.inputValue);
  };

  componentDidUpdate(prevProp) {
    if (prevProp.val === this.props.val) return
    // it will update input value for other input change
    this.setState({ inputValue: this.props.val })
  }

  render() {
    return (
      <div>
        <input
          spellCheck="false"
          // use value instead of DefaultValue
          value={this.state.inputValue}
          ref={this.inputRef}
          onKeyDown={e => this.handleKeyPress(e)}
          onBlur={e => this.handleBlur(e)}
          // add a onChange handler to update state
          onChange={ e => this.setState({inputValue : e.target.value}) }
        />
      </div>
    );
  }
}

Problem :

In App, I have a child component that has a child component which contains an <input>, and another child component which contains an <input>. The structure is as follows:

<App>
  <Parent>
    <ClassWithInput1 />
  </Parent>
  <ClassWithInput2 />
</App>

In App.state, I have a string val that can be set through either of the <input> fields, and is displayed using the defaultValue attribute in both <input> fields when it is updated.

When it is updated with ClassWithInput1, the value for the <input> in ClassWithInput2 is updated correctly. However, when I update it in ClassWithInput2, the changes are not reflected in ClassWithInput1. App.state.val is being updated correctly in both cases. I checked in the Chrome inspector, and the value attribute in the HTML is correct in ClassWithInput1, but the actual changes aren’t displayed on the page.

Here is a sandbox example of the issue: https://codesandbox.io/s/zen-thunder-z1p81?file=/src/App.js.

How can I fix this?

Comments

Comment posted by Jasper Huang

Thanks! Any reason as to why setting it as

Comment posted by buzatto

because

Comment posted by Jasper Huang

Thanks for the thorough answer!

By