How to add hover events to any React component

p and button tags aren't the only tags that can have hover events!

Thu, 01 Nov 2018

I was playing around with a layout for a project and needed to do something unconventional. Before that day I always thought you could only hover over button and a tags, turns out I was wrong!

Code

For this example we will use a p tag. We set the base colors of the p tag to black and when we hover, we change the color and the cursor to mimic what happens when a button or a tag is hovered.

There are 3 ways that we can achieve this

Styled-Components

Styled Components is one of my favorite libraries to use to style html.

yarn add styled-components

npm install styled-components

import styled from 'styled-components';

const HoverText = styled.p`
	color: #000;
	:hover {
		color: #ed1212;
		cursor: pointer;
	}
`

Further along in the class when its time to use your p tag you want to replace it with our HoverText component. Instead of

<p>Test</p>

You want to use

<HoverText>Test</HoverText>

Thats all, super easy!

Javascript Event Handlers

I wouldn’t use this method for basic cases. Real useful for some more complicated scenarios

constructor(props) {
	super(props)
	this.state = {
		hover: false
	}
}

toggleHover() {
	this.setState({hover: !this.state.hover})
}

render {
   var linkStyle;
   if (this.state.hover) {
     linkStyle = {color: '#ed1212',cursor: 'pointer'}
   } else {
     linkStyle = {color: '#000'}
   }
	return(
		<p style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Test</p>
	)
}

CSS

The CSS way is similar to styled-components. Inside your css file you just set it up like this

p {
	color: #000;
	:hover {
		color: #ed1212;
		cursor: pointer;
	}
}
Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge