I am trying to call a click event handler when I click on a NavItem using React-Bootstrap.
I have the following code:
<Navbar fluid inverse>
<Navbar.Header>
<Navbar.Brand>
{first} {last}
</Navbar.Brand>
<Navbar.Toggle/>
</Navbar.Header>
<Navbar.Collapse>
<Nav>
{navItems.map(item => {
return(
<NavItem
key={item[1]}
eventKey={item[1]}
onClick={()=> this.handleClick}
>
{item[0]}
</NavItem>
);
})}
</Nav>
</Navbar.Collapse>
</Navbar>
With this as my click handler:
handleClick(event) {
event.preventDefault();
console.log(event);
}
What's goofy, is that this doesn't work, however, when I have the onClick to equal:
<NavItem
key={item[1]}
eventKey={item[1]}
onClick={()=> console.log("Hello")}
>
{item[0]}
</NavItem>
It works fine, it is only when I add the click handler... any ideas?
The problem is that you are not calling the function you are returning it. replace this line:
onClick={()=> this.handleClick}
with:
onClick={()=> this.handleClick()}
also If you want to access event in your function you should pass it to your function:
onClick={e => this.handleClick(e)}
in arrow functions this:
() => this.someFunction
translates to:
var that = this
function() {
return that.someFunction
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With