2

I am new to reactjs and I am not able to figure how to change child component state from parent component. Below is the code

<ChildComponent productCode={this.state.productCode} />

I would like the child component receive the productCode whenever a setState is done on productCode in the parent component.

Publishing an event from the parent component and subscribing to the event in the child component is on top of my head.

Any suggestions?

zhulien
  • 5,145
  • 3
  • 22
  • 36
Krishna Chaitanya
  • 2,533
  • 4
  • 40
  • 74
  • Does this answer your question? [React Child Component Not Updating After Parent State Change](https://stackoverflow.com/questions/41233458/react-child-component-not-updating-after-parent-state-change) – zhulien Mar 10 '21 at 15:29

3 Answers3

1

This does work, but note that the Child receives this data as a prop, not as a part of its internal state.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  render() {
    return (
      <section>
        Count: {this.state.count}
        <br />
        <button
          onClick={() =>
            this.setState((prevState) => ({
              count: prevState.count + 1,
            }))
          }
        >
          Increment Count
        </button>
        <Child passedCount={this.state.count} />
      </section>
    );
  }
}

class Child extends React.Component {
  render() {
    return (
      <section>
        I am the child. The <code>count</code> * 2 ={' '}
        {/* Access `this.props.passedCount` to use the value */}
        <b>{this.props.passedCount * 2}</b>
      </section>
    );
  }
}

const rootElement = document.getElementById('root');
ReactDOM.render(<Parent />, rootElement);
section {
    background: beige;
    padding: 1em;
}

section > section {
    background: sandybrown;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
romellem
  • 5,792
  • 1
  • 32
  • 64
0

Assuming that childState is your child state, if you are working with class component you have to add to your class a componentWillReceiveProps hook life cycle.

componentWillReceiveProps(nextProps) {
  this.setState({ childState: nextProps.productCode});  
}
Anass TIssir
  • 240
  • 2
  • 7
0

You have run exactly into the reason why people use state containers. I can only suggest trying out redux, mobx or mobx-state-tree.

If you really don't want to dive into these tools, things get a little tricky, you can do it anyway if you insist, but I would advise against.

Proceed like this: first write a function in the parent that alters it state, then hand that function over to the child component, after that call that function in the child. Here is a code example, you might fiddle with it a little though:

// the parent
function parent() {
   const [state, setState] = useState('')

   const update = () => {
      setState("new state")
   }

   return(<Child updateFunction={update} />)
}

// the cild
function Child(props) {
   return(
      <FancyComponent
         onClick={props.update}
      />
   )
}
inchw0rm
  • 111
  • 7