Not getting proper output after clicking on Switch Name button in ReactJs

Viewed 83

Not getting proper output after clicking on Switch Name button in ReactJs

App.js:

        state = {
            persons: [
              { name: 'Max', age: 25 },
              { name: 'Manu', age: 29 },
              { name: 'Stephanie', age: 26 }
            ]
        }

        switchNameHandler = () => {
            console.log('Was clicked!');      
        }

        render() {
            return (
              <div className="App">
                <h1> Working................ </h1>
                <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
                <Person name="abc" age="20" />
                <Person name="uvw" age="20" />
                <Person name="uvw" age="20" />
                <Person name="lmno" age="20" >Working.........</Person>
                <button onClick={this.switchNameHandler()}>switch Name</button>
              </div>
            );
        }

Output: (after clicking 6-7 times)

log.js:24 [HMR] Waiting for update signal from WDS...
react-dom.development.js:24994 Download the React DevTools for a better development experience: .....
App.js:20 Was clicked!
App.js:20 Was clicked!
DevTools failed to load SourceMap: Could not load content for chrome-extension://gighmmpiobklfepjocnamgkkbiglidom/include.postload.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME
Grammarly.js:2 [DEFAULT]: WARN : Using DEFAULT root logger
2 Answers

Your issue is here.

<button onClick={this.switchNameHandler()}>switch Name</button>

You dont need the () at the end of function. If you have () the switchNameHandler function is executed and the return value (if any) of the function is assigned to the onClick handler.

You need to give onClick like this

<button onClick={this.switchNameHandler}>switch Name</button>

or

<button onClick={()=>this.switchNameHandler()}>switch Name</button>

onClick expects a function, not the return of a function unless the return is another function.

you need to make the function a variable, same with your object. Try this:

var state = {
    persons: [
      { name: 'Max', age: 25 },
      { name: 'Manu', age: 29 },
      { name: 'Stephanie', age: 26 }
    ]
  }
var switchNameHandler = () => {
  console.log('Was clicked!');
  
}
Related