Reputation: 2663
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?
Upvotes: 2
Views: 4853
Reputation: 111
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}
/>
)
}
Upvotes: 0
Reputation: 6491
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>
Upvotes: 1
Reputation: 240
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});
}
Upvotes: 0