showing results for - "how to make a buttom in react stackoverflow"
Elisa
31 Nov 2019
1const defaultStyle = {
2  width: 100,
3  padding: 5,
4};
5
6class MultiLevelButton extends React.Component {
7  constructor(props) {
8    super(props);
9    
10    this.state = {
11      currentState: 0,
12    };
13    
14    this.handleClick = this.handleClick.bind(this);
15  }
16  
17  handleClick() {
18    const { currentState } = this.state;
19    
20    if (currentState < this.props.states.length) {
21      this.setState({
22        currentState: currentState + 1,
23      });
24    }
25  }
26  
27  reset() {
28    this.setState({
29      currentState: 0,
30    });
31  }
32  
33  render() {
34    const { currentState } = this.state;
35    const { states } = this.props;
36    
37    return (
38      <button onClick={this.handleClick} style={{border: 'none', outline: 'none'}}>
39        {
40          states
41            .map((s, i) => {
42              const stateNumber = states.length - i;
43              const overrides = stateNumber <= currentState ? { backgroundColor: '#000', color: '#fff' } : {};
44              const style = {
45                ...defaultStyle,
46                backgroundColor: s,
47                ...overrides,
48              };
49              return <div style={{...style}}>{stateNumber}</div>
50            })
51        }
52      </button>
53    )
54  }
55}
56
57const buttonRef = React.createRef();
58
59ReactDOM.render(
60  <div>
61    <MultiLevelButton ref={buttonRef} states={['#bbb', '#ccc', '#ddd', '#eee', '#fff']} />
62    <MultiLevelButton states={['#fcc', '#cfc', '#ccf']} />
63    <div>
64      <button onClick={() => buttonRef.current.reset()}>Reset</button>
65    </div>
66  </div>,
67  document.getElementById('app')
68);