Skip to content

Instantly share code, notes, and snippets.

@mziwisky
Created November 1, 2017 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mziwisky/4ef212f12b464fb099344fdbbaaf7032 to your computer and use it in GitHub Desktop.
Save mziwisky/4ef212f12b464fb099344fdbbaaf7032 to your computer and use it in GitHub Desktop.
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