EN
React - add onClick to div (class component)
3 points
In this article, we would like to show you how to handle a mouse click event on div
element in React.
Below example uses:
- the component's state to store
color
value, setState()
method to update thecolor
,onClick
property to handle the event.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class App extends React.Component {
6
constructor(props) {
7
super(props);
8
this.state = {
9
color: 'yellow'
10
};
11
}
12
handleClick = () => {
13
this.setState({ color: this.state.color === 'yellow' ? 'orange' : 'yellow' });
14
};
15
render = () => {
16
return (
17
<div style={{ background: this.state.color }} onClick={this.handleClick}>
18
Click me to change my color.
19
</div>
20
);
21
};
22
}
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.