Skip to content

Instantly share code, notes, and snippets.

@alonbardavid
Created October 2, 2019 12:27
Show Gist options
  • Save alonbardavid/142ae79b8db39cf886201929a28c2076 to your computer and use it in GitHub Desktop.
Save alonbardavid/142ae79b8db39cf886201929a28c2076 to your computer and use it in GitHub Desktop.
Patterns for deriving state gist6
// ToppingSelection receives props with the following structure (Typescript notation):
// {options:{text:string,value:string},selected:string[],onChange:(value)=>void}
class ToppingSelection extends React.Component {
handleInputChange = (event)=>{
const value = event.target.name;
if ( selected.includes(value)){
onChange(selected.filter(option=>option !== value));
} else {
onChange(selected.concat(value));
}
}
render(){
const {options,selected} = this.props;
return <div>
{options.map(option=>
<label key={option.value}>
{option.text}
<input type={checkbox} checked={selected.includes(option.value)}
onChange=(this.handleInputChange} name={option} />
</label>
)}
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment