Kuan
Kuan

Reputation: 11389

How to handle mouse event in stateless component in React

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

Upvotes: 5

Views: 5002

Answers (2)

StJungDev
StJungDev

Reputation: 45

What about using classic CSS for simple hover effects?

<div class="el-to-hover"></div>

somewhere in css-file:

.el-t-hover {
   background: transparent
   transition: background .3s ease-in-out;
}
.el-to-hover:hover {
   background: red
}

Upvotes: 0

QoP
QoP

Reputation: 28397

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

Upvotes: 7

Related Questions