##Exercise 6: Hold Toggle state in the component
- Use a property initializer (experimental ES7 syntax) to define the initial state
of the component right above the
rendermethod in theTogglecomponent.
// app/components/Toggle.js
state = {
enabled: false
};
render() {
// ...
}- Use component
stateto determine the value theToggledisplays in the render method. Changethis.props.enabledtothis.state.enabled.
// app/components/Toggle.js
{this.state.enabled ? this.props.enabledText : this.props.disabledText}:- Update the click handler so it toggles the
enabledstate of theToggle. Whenever the state of a component changes, React re-renders that component. We'll also change the handler to a property initializer to preserve the context.
// app/components/Toggle.js
_handleClick = (event) => {
this.setState({ enabled: !this.state.enabled })
};-
Try clicking on your
Togglein the page. You should see it toggling between values. -
Remove
enabledfrom thepropTypesanddefaultPropssince we're no longer using it.
// app/components/Toggle.js
static propTypes = {
enabledText: PropTypes.string,
disabledText: PropTypes.string
};
static defaultProps = {
enabledText: 'ON',
disabledText: 'OFF'
};- Also, remove the property from the
Toggleelement inapp/main.js.
// app/main.js
render(<Toggle enabledText='Yep' disabledText='Nope' />, document.getElementById('app'))###[Next Step: Add CSS to `Toggle` →](./exercise-7.md)