Roy Prins
Roy Prins

Reputation: 3080

Props of a child component are not coupled with state of parent

I have a parent component (App) that holds the state. Inside this component I have some code that manipulates the state through event handlers. So far so good.

However, I need to display the current state inside a child component (ChildComponent). I tried to achieve this by passing the state as a property to the ChildComponent, however I lose the dynamic coupling to the state. Any change to state is not reflected in the child component.

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render () {
        // This should get dynamically updated
        return <div>{this.props.value.toString()}</div>
    }
}


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
    }

    // Do stuff here that changes state

    render() {
         return <ChildComponent value={this.state.value} />
    }
}

works now: Updated correct example on codepen

This example is a basic representation of my problem. I think I followed the example of the official docs, and specifically lifting state up. Somehow it does not work though. Could be me misinterpreting the docs (those also happen to be not so good).

edit: maybe having to do with the child component being a class rather than a function?

Upvotes: 0

Views: 66

Answers (3)

Petr Lazarev
Petr Lazarev

Reputation: 3182

This works as you expected:

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render () {
        // This should get dynamically updated
        return <div>{this.props.value.toString()}</div>
    }
}


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
        this.addOne = this.addOne.bind(this);
    }

    addOne(event){
      this.setState({value: this.state.value+1})
      console.log(this.state.value)
    }

    // Do stuff here that changes state

    render() {
         return (
             <div>
                 <button onClick={this.addOne}>add 1</button>
                 <ChildComponent value={this.state.value} />
             </div>
         )
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

You can test it here.

Upvotes: 0

Nick
Nick

Reputation: 1570

You should use setState. setState always triggers a re-render:

https://codepen.io/anon/pen/gmOzXg

Upvotes: 1

Andy_D
Andy_D

Reputation: 4228

You should not mutate the state of a component directly (this.state.x = this.state.x + 1), but use setState.

See this question for additional info, and what the React docs used to say on the subject.

Upvotes: 1

Related Questions