Reputation: 45
I am trying to show an alert onclick of an element that is conditionally rendered but the onclick event doesn't work i took the code out of the ternary operator and it worked but i cna't seem to find the reason why it didn't work in the ternary operator.
import React from 'react';
import HomeIcon from '../Images/home.svg'
import HomeIconBlue from '../Images/home-blue.svg';
function Menubar(props) {
const style = {
borderTop: "3px solid #2D79BB",
color: "#2D79BB",
}
return (
<div className="menu-bar">
<div className="home-icon">
{
(props.active === 'home') ?
<span style={style} onClick={alert('hey')}>
<img src={HomeIconBlue} alt="home" />
<p>Home</p>
</span> :
<span>
<img src={HomeIcon} alt="home" />
<p>Home</p>
</span>
}
</div>
)
}
export default Menubar
Upvotes: 1
Views: 889
Reputation: 153
The element you kept the onClick event is not yet rendered keep it on the second element. The one currently being rendered
return (
<div className="menu-bar">
<div className="home-icon">
{
(props.active === 'home') ?
<span style={style} >
<img src={HomeIconBlue} alt="home" />
<p>Home</p>
</span> :
<span onClick={alert('hey')}>
<img src={HomeIcon} alt="home" />
<p>Home</p>
</span>
}
</div>
)
Upvotes: 1
Reputation: 71
Try changing the onClick from
onClick={alert('hey')}
To
onClick={() => alert('hey')}
Upvotes: 3