Use state and some events to change the background of a <div> as the mouse hovers on it.


Very easy


We are all familiar with the CSS :hover pseudo-class, aren't we? It simply defines some styles to execute when the mouse pointer hovers over an element.

For instance, let's suppose we have the following <div> along with the following CSS:

<div>Change the background</div>
div {
   background-color: #eee;

div:hover {
   background-color: yellow

Thanks to div:hover, the moment we hover over the <div>, its background changes to yellow, and then when the mouse leaves, the background changes back to #eee.

Now as you may know, :hover could be emulated using JavaScript as well, in particular, using mouse events. Remember the two events used to emulate :hover? Well, they are mouseenter and mouseleave.

But this exercise isn't about :hover or about JavaScript; it's all about React and getting better at its foundational concepts. Right?

So in this exercise, you have to create a <div> that changes its background to yellow everytime the mouse hovers over, and then resets it back as soon as the mouse leaves, without using :hover.

Here are two points to consider when styling the <div>:

  • It should have a height of 200px.
  • Its initial background color should be #eee.