Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Bootstrap NavItem not Firing onClick Handler

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?

like image 602
bflynnigan Avatar asked Mar 03 '26 06:03

bflynnigan


1 Answers

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)}

A little more explanation

in arrow functions this:

() => this.someFunction

translates to:

var that = this
function() {
  return that.someFunction
}
like image 113
Soorena Avatar answered Mar 05 '26 02:03

Soorena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!