EN
React - add onClick to div
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:
React.useState()
hook to storecolor
.onClick
property to handle the event.
Practical example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const [color, setColor] = React.useState('yellow');
7
const handleClick= () => {
8
setColor(color === 'yellow' ? 'orange' : 'yellow');
9
}
10
return (
11
<div style={{ background: color }} onClick={handleClick}>
12
Click me to change my color.
13
</div>
14
);
15
}
16
const root = document.querySelector('#root');
17
ReactDOM.render(<App/>, root );
Note: go to this article to see class component version.