##Exercise 9: Update Toggle state in the Settings component
- Define the
Settingscomponent initial state above therendermethod. We're going to keep track of which settings are enabled.
// app/components/Settings.js
state = {
enabled: []
}
render() {
// ...
}- Add two functions in
_renderToggleto handle when aToggleis enabled and disabled. We'll update theSettingsstate in these functions. We'll also need to change_renderToggleinto property initializer to preserve the context.
// app/components/Settings.js
_renderToggle = (label, index) => {
const handleEnable = () => {
// Copy the enabled list, add this index number, and set the new enabled state
this.setState({ enabled: this.state.enabled.concat([index]) })
}
const handleDisable = () => {
const enabled = this.state.enabled.slice() // Copy the enabled list
enabled.splice(index, 1) // Remove the item at this index
this.setState({ enabled }) // Set the new enabled state
}
return (
// ...
};- Add two properties to the
Toggleelement inSettings,onEnabledandonDisabled, and bind them tohandleEnableandhandleDisable.
// app/components/Settings.js
_renderToggle = (label, index) => {
// ...
return (
<Toggle
key={index}
enabledText='Yep'
disabledText='Nope'
onEnable={handleEnable}
onDisable={handleDisable}
>
{label}
</Toggle>
)
}- Add some debugging elements to
Settingsafter interating through toggles inrender.
// app/components/Settings.js
render() {
// ...
return (
<div className={css.settings}>
<h1 className={css.heading}>Settings</h1>
{settings.map(this._renderToggle)}
<div className={css.debug}>
Enabled: {this.state.enabled.length ? this.state.enabled.join(', ') : 'None'}
</div>
</div>
)
}- In the
Togglecomponent, addonEnabledandonDisabledtopropTypesanddefaultProps.
// app/components/Toggle.js
static propTypes = {
enabledText: PropTypes.string,
disabledText: PropTypes.string,
onEnable: PropTypes.func,
onDisable: PropTypes.func
};
static defaultProps = {
enabledText: 'ON',
disabledText: 'OFF',
onEnable() {},
onDisable() {}
};- In
_handleClick, add a callback tosetStatethat invokes the correct event handler in props.
// app/components/Toggle.js
_handleClick = (event) => {
this.setState({ enabled: !this.state.enabled }, () =>
this.state.enabled ? this.props.onEnable() : this.props.onDisable()
)
};- Check to see that
Settingsis correctly updated with which toggles are enabled. The settings view should list which items are enabled.
###[Next Step: Use JSON to populate `Settings` component →](./exercise-10.md)