<div id="root"></div>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
background-color:black;
}
button {
display: block;
margin: 20px auto;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
class ColorChanger extends React.Component {
constructor(props) {
super(props);
this.divRef = React.createRef();
this.colors = ['#FFCDD2', '#C8E6C9', '#BBDEFB', '#FFF9C4', '#D1C4E9'];
this.state = { colorIndex: 0 };
this.changeColor = this.changeColor.bind(this);
}
changeColor() {
const nextColorIndex = (this.state.colorIndex + 1) % this.colors.length;
this.setState({ colorIndex: nextColorIndex });
this.divRef.current.style.backgroundColor = this.colors[nextColorIndex];
}
render() {
return (
<div>
<div
ref={this.divRef}
style={{
width: '200px',
height: '200px',
backgroundColor: this.colors[this.state.colorIndex],
margin: '20px auto',
}}
></div>
<button onClick={this.changeColor}>Change Color</button>
</div>
);
}
}
root.render(<ColorChanger />);
View Compiled
This Pen doesn't use any external CSS resources.