Reputation: 125
When I enter the mouse on body I want to change the background-color
of a page with React
What should I do?
Upvotes: 0
Views: 863
Reputation: 198
I wrote simple functional component to show the idea. There is a method in react onMouseEnter which you can use to set state if the mouse enter on an element and then use that state to change the background. I add a class on the element if the mouse enter, you could also use onMouseLeave method to remove the background if mouse leaves the element. You could use this idea in root of your component to change entire background screen.
import React from 'react';
import { useState } from 'react';
// Styles
import '../src/styles/style.scss';
const BgChangeMouseEvent = () => {
const [isEnterMouse, setIsEnterMouse] = useState(false);
const handleBackground = state => {
setIsEnterMouse(state);
};
return (
<div
className={isEnterMouse ? 'background' : ''}
onMouseEnter={() => handleBackground(true)}
onMouseLeave={() => handleBackground(false)}
>
<h1>Changing background from mouse Enter</h1>
</div>
);
};
export default BgChangeMouseEvent;
For more information please read this link from the official react web site. https://reactjs.org/docs/events.html#mouse-events
Upvotes: 1