Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle mouse event in stateless component in React

Tags:

reactjs

All:

I wonder if I use stateless component, how can I handle mouse event to change component style, for example:

const Com = (props) => {
    var hltStyle = false;
    function highlight(){
        // I do not know what put here
    }

    var hltStyle = {
        backgroundColor: !hltStyle?"lightgreen": "tomato"
    }

    return (
        <div style={hltStyle} onMouseOver={ highlight } >HOVER ME</div>
    )
}

What I want just hover this component and change background color. There is some other logic inside highlight, that is why I can not simply use CSS

Thanks

like image 672
Kuan Avatar asked Jun 07 '16 22:06

Kuan


People also ask

How do you use mouse event in react?

When user press the mouse button down, a mousedown event is triggered, and when user release, a mouseup event is triggered. The handleEvent method uses the type property to determine which event is being handled and updates the message value accordingly.

Can stateless components have functions?

A stateless function component is a typical React component that is defined as a function that does not manage any state. There are no constructors needed, no classes to initialize, and no lifecycle hooks to worry about. These functions simply take props as an input and return JSX as an output.


1 Answers

You can achieve that using something like this

const Com = () => {
        function over(e){
                e.target.style.backgroundColor="red";
        }
        function out(e){
                e.target.style.backgroundColor='';
        }
        return <div onMouseOver={over} onMouseOut={out}>HOVER ME </div>;
}

Anyway, if you feel that you need to declare some variables to use them as the state, you should use a normal component instead of a stateless one.

jsfiddle

like image 176
QoP Avatar answered Oct 05 '22 00:10

QoP