Skip to content

Instantly share code, notes, and snippets.

@tdeekens
Created April 28, 2018 14:12
Show Gist options
  • Save tdeekens/472ba9f991e96b08aef7f811359b562a to your computer and use it in GitHub Desktop.
Save tdeekens/472ba9f991e96b08aef7f811359b562a to your computer and use it in GitHub Desktop.
const RadioContext = React.createContext();
class RadioGroup extends React.Component {
// NOTE:
// That we memoize the value in oder not to trigger wasteful rendering on
// the `RadioContext.Provider` below.
createContextValue = memoize((value, name, onChange) => ({
value,
name,
onChange
}));
render() {
return (
<RadioContext.Provider
value={createContextValue(
this.props.value,
this.props.name,
this.props.onChange
)}
>
{this.props.children}
</RadioContext.Provider>
);
}
}
class RadioOption extends React.Component {
render() {
return (
<RadioContext.Consumer>
{radioGroup => (
<input
type="radio"
name={radioGroup.name}
checked={radioGroup.value === this.props.value}
onChange={radioGroup.onChange}
/>
)}
</RadioContext.Consumer>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment