I need to render a widget
which takes in settings from a SettingsPanel
and passes them to a LayoutPanel
(which would then re-render itself based on the updated settings). I can't seem to figure a 'clean' way to do this. Here's what I have so far:
Widget.js
class Widget extends Component {
handleSettingsChange() {
//need to let layout know of change
}
render() {
<div>
<SettingsPanel
onSettingsChange={handleSettingsChange}
initialSettings={this.props.settings}
/>
<Layout
data={ this.props.data}
/>
</div>
}
}
App.js
const settings = {
hideImages: true,
itemsPerPage: 5
}
<Widget settings={ settings } data={ data } />
My first thought was that, within Widget, I could do
constructor() {
super()
this.setState({ settings: this.props.settings });
}
handleSettingsChange(data) {
//Assuming data is of the form {changedProperty: value}
this.setState({ settings: Object.assign({}, this.state.settings, data) });
}
render() {
<div>
<SettingsPanel
onSettingsChange={handleSettingsChange}
initialSettings={this.props.settings}
/>
<Layout
data={ this.props.data}
settings={ this.state.settings }
/>
</div>
}
This way the parent is a dump message broker, and doesn't not have to know the specifics of what specific settings are being change. But of course, this doesn't work because, a. I'm told setting state from props is an anti-pattern b. The constructor doesn't have access to this.props anyway, and doing it else-where (componentDidMount?) feels wrong.
My second thought was to go to setProps
to set props on children from the parent, but of course that's deprecated.
How do I solve this? I could probably re-architect this so this isn't a problem, but frankly I'd just like to understand what I'm missing, or what the 'react' way of solving things like this is.
This question is similar to the same problem I'm having but I'm having trouble understanding/applying what the accepted solution suggests to my problem.
tldr; "How can I make a parent component pass state from one child to another, while being ignorant of what exactly it's passing?"