0

I have his code where i try to pass a variable to the handleclick fcn and set state to that variable:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'Initial State'
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(temp) {
    this.setState({
      name:temp
    });
  }
  render() {
    return (
      <div>
        <button onClick={this.handleClick('name')}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
};

It doesn't work, can someone explain how to pass a variable and set state to it, if it's possible??

0

1 Answer 1

2

By writing this.handleClick('name') you are invoking the handleClick function directly on render. You want to give a function to the onClick prop that will be invoked on click.

Example

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "Initial State"
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(temp) {
    this.setState({
      name: temp
    });
  }
  render() {
    return (
      <div>
        <button onClick={() => this.handleClick("name")}>Click Me</button>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, thank you!i tried marking this as the answer but i have to wait 10 mins
This will result in creating an arrow on each render which is undesirable if it's possible to avoid this.
So what would be a better solution?
@Jrobm2k9 Don't worry about it. If your use case absolutely demands that you prematurely optimize it, you can use a data attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.