Pass variable in react

4183 views reactjs
-1

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??

answered question

There's no variable. 'name' is a string. Is it your real code? The solution may depend on it.

1 Answer

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>

posted this

Have an answer?

JD

Please login first before posting an answer.