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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const [color, setColor] = React.useState('yellow');
const handleClick= () => {
setColor(color === 'yellow' ? 'orange' : 'yellow');
}
return (
<div style={{ background: color }} onClick={handleClick}>
Click me to change my color.
</div>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );
Note: go to this article to see class component version.