-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle.js
40 lines (35 loc) · 1.08 KB
/
toggle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React from "react";
export class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: false, someOther: false };
// This binding is necessary to make `this` work in the callback
//// this.handleClick = this.handleClick.bind(this);
}
componentWillUpdate(nextProps, nextState){
if(this.state.isToggleOn !== nextState.isToggleOn){
this.props.onChange({
isToggleOn: nextState.isToggleOn,
id: nextProps.id
});
}
}
handleClick = (e) => {
e.preventDefault();
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick} style={{
padding: "0px 10px",
margin: "2px 5px",
background: this.state.isToggleOn ? "green" : "red",
width: "60px"
}}>
{this.state.isToggleOn ? "On" : "Off"}
</button>
);
}
}