-2

I am a newbie who just started studying React.

I am very confused with bind() method that is used within onClick inside the component tag.

Below is the snippet of my code. This code works, but I am not really sure what bind() is doing and how is it working.

When I click the button, I am passing "Jack" as the argument of switchNameHandler method.

When the switchNameHandler is executed, what is inside the argument newName? And what are this referring to inside the switchNameHandler method and bind(this, 'Jack') line? What exactly is bind(this, 'Jack') doing?

...
switchNameHandler = (newName) => {
 this.setState({
  persons: [
    {name: newName, age: 21},
     ]
    });
  }

render() {
 return (
  <div className="App">
    <button onClick={this.switchNameHandler.bind(this, 'Jack')}>Switch Name</button>
    <Person 
      name={this.state.persons[0].name} 
      age={this.state.persons[0].age}></Person>
   </div>
    );
  }
...
  • Since you are actually using the arrow function for switchNameHandler. Please try by removing bind? – Sim Sep 08 '20 at 12:08

1 Answers1

0
  1. Paste console.log(newName) in your switchNameHandler function before this.setState -> it should print some info in devtool -> console

  2. Some info about bind(): https://javascript.info/bind

Nienormalny_
  • 460
  • 3
  • 14