0

In React, I am trying to send a JavaScript object from a parent component to a child component, but I also want the changes to that object in the child component to be visible in the parent component. I am trying to use the concept of props but it doesn't seem to work. What could be wrong here?

So basically:

class ParentComponent extends React.Component {

   constructor(){}

   render() {

   return <ChildComponent exampleObject={"Example"}> </ChildComponent>

             }

}


class ChildComponent extends React.Component {

   constructor (props) {
   super();
   this.state={myState: props.exampleObject}
                     }

render() {

   this.state.myState="Example 2";
   console.log(this.state.myState);
   return <div></div>
         }

}

The console.log in the child component simply outputs: undefined, even when I remove changing the value of its state variable.

Ibrahim7
  • 113
  • 2
  • 7
  • Does this answer your question? [How to pass data from child component to its parent in ReactJS?](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Emile Bergeron Aug 25 '21 at 20:57
  • It's known as [lifting the state up](https://reactjs.org/docs/lifting-state-up.html). – Emile Bergeron Aug 25 '21 at 20:58
  • @EmileBergeron I want to send an object from parent to child (not the other way around) access it in the child component and change its value. Sounds very simple but it doesn't work for some reason that I don't understand (I'm quite a beginner) – Ibrahim7 Aug 25 '21 at 21:08
  • I'm not sure if this has any impact, but *"When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement."* - [React.Component](https://reactjs.org/docs/react-component.html#constructor) – 3limin4t0r Aug 25 '21 at 21:11

1 Answers1

0

You can not change state like this.

 this.state.myState="Example 2";

The only way to change the state is to use setState.

And use lifecycle function like componentDidUpdate to update state based on props changes.

componentDidUpdate (prevProps, prevState) {
    if (prevProps.exampleProps !== this.props.exampleProps) {
        this.setState({myState: this.props.exampleProps})
    }
}
 
Chuck
  • 776
  • 5
  • 18
  • Thank you very much, although it still does not work even if I omit the code for changing the state. If I just want to console.log(this.state) in the child component, the value is still undefined – Ibrahim7 Aug 25 '21 at 21:54