user3862110
user3862110

Reputation: 1

Change inline color on mouseover (React)

How can I make this to change only the element that has mouseovered and not by ids? Following is my code component that changes the text color randomly from an array when mouseover.

class Chroma extends React.Component {
constructor(props) {
super(props)
}
mouse = event => {
var colorhex = [
'#7AF377', '#3498DB', '#F1C530', '#F29C29', '#8E44AD', '#4AA086', '#E74C3C', '#65CC71','#D3541B','#EB4367','#74F7D9', '#DDA8FC',
]
var el = document.getElementById('colorstext')
el.style.color = colorhex[Math.floor(Math.random() * 12)]
}
mouseout = event => {
var white = '#FFFFFF'
var el = document.getElementById('colorstext')
el.style.color = white
}

render() {
return (

<a
href={this.props.link}
onMouseEnter={this.mouse}
onMouseLeave={this.mouseout}
id="colorstext"
>
{this.props.text}
</a>
)
}
}
export default Chroma

Upvotes: 0

Views: 13237

Answers (2)

pizza0502
pizza0502

Reputation: 343

event.target is the simplest way to get this done.

But I notice that you didn't bind your mouse actions, you need to bind the mouse and mouseout like this: onMouseEnter={(event) => mouse(event)}

Here is the working example: https://codesandbox.io/s/n5jvrkxxwp

Upvotes: 5

J.Lindebro
J.Lindebro

Reputation: 223

Try using the info following in the event object:

const mouse = event => {
   const el = event.target // instead of getElementById('colorstext')
   .... your code
 }

Upvotes: 1

Related Questions