Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
comparison of using props vs invoking a method to tell a child component to focus something
Child = React.createClass({
focusThing () {
this.btn.focus();
},
render () {
return (
<div>
Here's the thing to <button ref={ el => this.btn = el }>focus</button>
</div>
);
}
});
Parent = React.createClass({
focusSomethingInChild () {
this.child.focusThing();
},
render () {
return (
<div>
<button onClick={ this.focusSomethingInChild }>Focus</button>
<Child
ref={ el => this.child = el }
/>
</div>
);
}
});
Child = React.createClass({
propTypes: {
needsFocus: React.PropTypes.bool
},
maybeFocus (el) {
if (el && this.props.needsFocus) {
el.focus();
}
},
render () {
return (
<div>
Here's the thing to <button ref={ this.maybeFocus }>focus</button>
</div>
);
}
});
Parent = React.createClass({
getInitialState () {
return {
childNeedsFocus: false
};
},
focusSomethingInChild () {
this.setState({
childNeedsFocus: true
}, () => {
this.setState({
childNeedsFocus: false
});
});
},
shouldComponentUpdate (nextProps, nextState) {
const { childNeedsFocus: childNeedsFocusIs, ...currentState } = this.state;
const { childNeedsFocus: childNeedsFocusWillBe, ...nextState } = nextState;
const onlyFocusWasReset =
_.isEqual(this.props, nextProps) &&
_.isEqual(currentState, nextState) &&
childNeedsFocusIs && !childNeedsFocusWillBe;
return !onlyFocusWasReset;
},
render () {
return (
<div>
<button onClick={ this.focusSomethingInChild }>Focus</button>
<Child
needsFocus={ this.state.childNeedsFocus }
/>
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment