Change Inline Color on Mouseover (React)

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

2 Answers

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:

Try using the info following in the event object:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.