Update Toggle

This commit is contained in:
Angelos Chalaris
2019-02-12 21:22:50 +02:00
parent d170e23ec2
commit 8095487476

View File

@ -2,49 +2,30 @@
Renders a toggle component.
Initialize `state.isToggleOn` to `false`, bind the `handleClick` method to the component's context.
Use the `React.useState()` to initialize the `isToggleOn` state variable to `false`.
Use an object, `style`, to hold the styles for individual components and their states.
Create a method, `handleClick`, which uses `Component.prototype.setState` to change the component's `state.toggleOn`.
In the `render()` method, destructure `state` and `style`, create a `<button>` that alters the component's `state` and determine the appearance of the content based on `state.isToggleOn`, applying the appropriate CSS rules from the `style` object.
Return a `<button>` that alters the component's `isToggledOn` when its `onClick` event is fired and determine the appearance of the content based on `isToggleOn`, applying the appropriate CSS rules from the `style` object.
```jsx
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: false
};
this.style = {
function Toggle(props) {
const [isToggleOn, setIsToggleOn] = React.useState(false);
style = {
on: {
backgroundColor: 'green'
backgroundColor: "green"
},
off: {
backgroundColor: 'grey'
backgroundColor: "grey"
}
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
const { isToggleOn } = this.state;
const { on, off } = this.style;
return (
<button
onClick={this.handleClick}
style={isToggleOn ? on : off}
onClick={() => setIsToggleOn(!isToggleOn)}
style={isToggleOn ? style.on : style.off}
>
{isToggleOn ? 'ON' : 'OFF'}
{isToggleOn ? "ON" : "OFF"}
</button>
);
}
}
```