Created
October 2, 2019 12:26
-
-
Save alonbardavid/2de4746e2915b5915e38d4ab6a8d4a77 to your computer and use it in GitHub Desktop.
Patterns for deriving state gist5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ToppingSelection receives props with the following structure (Typescript notation): | |
// {options:{text:string,value:string},selected:string[],onChange:(value)=>void} | |
class ToppingSelection extends React.Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
optionsWithSelect:_.cloneDeep(props.options) // _ is for lodash, which I use for clarity | |
} | |
} | |
handleInputChange = (event)=>{ | |
const value = event.target.name; | |
const {optionWithSelect} = this.state; | |
const index = optionWithSelect.indexOf(o=>o.value ===value); | |
if (optionWithSelect[index].selected){ | |
this.uncheckOption(index); | |
} else { | |
this.checkOption(index); | |
} | |
} | |
uncheckOption(index){ | |
const optionWithSelect = _.cloneDeep(this.state.optionWithSelect); | |
optionWithSelect[index].selected = false; | |
this.setState({ | |
optionWithSelect | |
}) | |
this.props.onChange(optionWithSelect.filter(o=>o.selected).map(o=>({text:o.text,value:o.value})) | |
} | |
checkOption(index){ | |
const optionWithSelect = _.cloneDeep(this.state.optionWithSelect); | |
optionWithSelect[index].selected = true; | |
this.setState({ | |
optionWithSelect | |
}) | |
this.props.onChange(optionWithSelect.filter(o=>o.selected).map(o=>({text:o.text,value:o.value})) | |
} | |
render(){ | |
const {optionsWithSelect} = this.state; | |
return <div> | |
{options.map(option=> | |
<label key={option.value}> | |
{option.text} | |
<input type={checkbox} checked={optionsWithSelect.checked} | |
onChange=(this.handleInputChange} name={option.value} /> | |
</label> | |
)} | |
</div> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment