Languages
[Edit]
EN

React - add onClick to div

3 points
Created by:
Zoya-Gaines
653

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 store color.
  • 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. 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - add onClick to div
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join