I have been working on building an app, where an uncommon scenario has raised for me to handle. I had to pass props to a child component from the parent, and the child component needs to set those props as its state.
<ChildComponent allProps={parentProps}>
<SomeChildren withProps />
</ChildComponent>
In the ChildComponent
:
class ChildComponent extends Component {
state: {
someRequiredProps: null
}
setStateForThisComponent(propsToSet) {
this.setState({someRequiredProps: propsToSet});
}
componentDidMount() {
this.props.allProps()
}
render() {
//I know this is incorrect syntax
return (<div allProps={(propsArg) => this.setStateForThisComponent(propsArg)});
}
}
Usually, I can run this method from parent component using refs
, but since this ChildComponent
being a very heavily reused component, I do not want to go with the refs
approach. Some other solutions suggested, that I create the state in parent component itself, and pass it as props to ChildComponent
, but that is not what I am trying to achieve.
Please let me solve this issue of setting the child component's state using the parent's.