Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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