983 B
983 B
title, tags
| title | tags |
|---|---|
| Toggle | components,state,beginner |
Renders a toggle component.
- Use the
React.useState()to initialize theisToggleOnstate variable todefaultToggled. - Use an object,
style, to hold the styles for individual components and their states. - Return a
<button>that alters the component'sisToggledOnwhen itsonClickevent is fired and determine the appearance of the content based onisToggleOn, applying the appropriate CSS rules from thestyleobject.
const Toggle = ({ defaultToggled = false }) => {
const [isToggleOn, setIsToggleOn] = React.useState(defaultToggled);
const style = {
on: {
backgroundColor: 'green'
},
off: {
backgroundColor: 'grey'
}
};
return (
<button onClick={() => setIsToggleOn(!isToggleOn)} style={isToggleOn ? style.on : style.off}>
{isToggleOn ? 'ON' : 'OFF'}
</button>
);
};
ReactDOM.render(<Toggle />, document.getElementById('root'));