javascript - React: Using parent to pass data between sibling components -
i need render widget takes in settings settingspanel , passes them layoutpanel (which re-render based on updated settings). can't seem figure 'clean' way this. here's have far:
widget.js
class widget extends component { handlesettingschange() { //need 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 that, within widget, do
constructor() { super() this.setstate({ settings: this.props.settings }); } handlesettingschange(data) { //assuming data 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 parent dump message broker, , doesn't not have know specifics of specific settings being change. of course, doesn't work because, a. i'm told setting state props anti-pattern b. constructor doesn't have access this.props anyway, , doing else-where (componentdidmount?) feels wrong.
my second thought go setprops set props on children parent, of course that's deprecated.
how solve this? re-architect isn't problem, frankly i'd understand i'm missing, or 'react' way of solving things is.
this question similar same problem i'm having i'm having trouble understanding/applying accepted solution suggests problem.
tldr; "how can make parent component pass state 1 child another, while being ignorant of it's passing?"
it's not true setting state props anti-pattern. seems reasonable initialize component's state props in constructor. doing doesn't degrade testability or reliability if @ all.
you can access props in constructor passed first parameter. you'll need call super first, can whatever you'd like:
class widget extends react.component { constructor(props) { super(props); this.setstate({ settings: props.settings }); } } then can continue down path headed. more complex option use state container redux handle state management , transitions you, if don't mind additional learning , complexity of adding more app setup.
Comments
Post a Comment