React js onClick property of NavDropdown.Item react- bootstrap

My code

<NavDropdown title="Theme" id="basic-nav-dropdown">
          <NavDropdown.Item href="#action/3.1">Dark Mode</NavDropdown.Item>
          <NavDropdown.Item href="#action/3.2">Light Mode</NavDropdown.Item>
          <NavDropdown.Item href="#action/3.3">Green Slate</NavDropdown.Item>
 </NavDropdown>

if i put onClick = {console.log("First button clicked)} inside NavDropdown.Item/> it outputs on console First button clicked without even clicking it. ??? Why ?? .

How can i use the onClick property to change some state ?

Hello there.

This behaviour is the same reason that, when you add a callback function to an element, you pass in the declaration, and not the function call. Example:

const myComp = () => {
  const [myState, setMyState] = React.useState(0);
  const callbackFunc = () => {
    console.log("Logged");
    setMyState(2);
  }
  return(
    <div>
       <button onClick={callbackFunc}>Click me to log</button>
       <button onClick={callbackFunc()}>I have already invoked the callback</button>
    </div>
  )
}

This is covered in the React section of the www.freeCodeCamp.org/learn course. But the above example also includes this…

I hope this helps

Hello
I did this and it’s not working pls help
i added this piece of code inside App.js

clickThemeFunc() {
    console.log("button is clicked");
    this.setState({ click: !this.state.click });
    console.log("value of theme: ", this.state.clickTheme);
  }
this.state = {
      textMarkdown: "This is inital state text",
      clickTheme: false
    };

Inside Navbar.js i added

 <NavDropdown.Item onClick={props.clickThemeFunc} href="#action/3.1">
            Dark Mode
          </NavDropdown.Item>

still i can’t any seething on console why ??

I highly recommend you review the React section of the curriculum.

this.setState({ click: !this.state.click });

You cannot set click as a state using its value, when you have not declared it - this.state.click does not exist.

Also, you have two methods in a class component, but only one of them you have bound with this.

clickThemeFunc={this.clickThemeFunc}
// You have not set 'this' to be related to the function handle

Ok so it was a typing mistake sorry for that.

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      textMarkdown: defaultMarkup,
      clickTheme: false
    };

    this.handleTextChange = this.handleTextChange.bind(this);
    this.clickThemeFunc = this.clickThemeFunc.bind(this);
  }
  clickThemeFunc() {
    console.log("button is clicked");
    this.setState({ clickTheme: !this.state.clickTheme });
    console.log("value of theme: ", this.state.clickTheme);
  }


Can you tell why is it still not working ? I cannot see anything on console.

I cannot see why the onClick is not firing. I have never used React-Bootstrap, but I assume the issue is there.

Sorry, I could not help any further.