Oftentimes, we want to add click event handlers to div elements in our React components.
In this article, we’ll look at how to add click event handlers to div elements in our React components.
Add Click Event Handlers for Divs in React
We can use onClick with divs if we provide it a size.
For instance, we can write:
class App extends React.component {
constructor() {
this.state = {
color: 'black'
};
},
changeColor() {
const newColor = this.state.color == 'white' ? 'black' : 'white';
this.setState({
color: newColor
});
},
render() {
return (
<div>
<div
style = {{
background: this.state.color,
width: 100,
height: 100
}}
onClick = {this.changeColor}
>
</div>
</div>
);
}
}
We create a div with a background by passing in an object with the styles in the style prop.
We set the width and height to 100px so that we can display a div with nothing inside.
Then we can pass in a click handler to the onClick prop.
In the changeColor method, we just toggle between white and black for the color state.
Conclusion
We can use onClick with divs if we provide it a size.