0

JSX

<a onClick={this.handleSave.bind(this)}/></a>

Function

handleSave(param){

}

How to pass param from Jsx to my handleSave function? I did not set everything in state. The a tag is a children of another component.

2
  • 1
    Use this.handleSave.bind(this, param) or If you want you can use ES6 arrow function. onClick={() => handleSave(param)} See this answer on how to use arrow functions. Commented Feb 12, 2017 at 6:31
  • 1
    Possible duplicate of React js onClick can't pass value to method Commented Feb 12, 2017 at 6:37

4 Answers 4

1

You can set arguments while calling bind

class App extends Component {
  handleClick(name){
    alert(this.props.appName + " : " + name);
  }
  render() {
    return (
      <div className="App">
        <a onClick={this.handleClick.bind(this, this.props.appName)} >Click Here</a>
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

It is not a good practice to bind functions on JSX elements, you should bind them on the constructor, that way, it wont generate a function on every render:

class App extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this, this.props.appName);
  }
  handleClick(name){
    alert(this.props.appName + " : " + name);
  }
  render() {
    return (
      <div className="App">
        <a onClick={this.handleClick}>Click Here</a>
      </div>
    );
  }
}

Comments

0

Based on the name of your function, I presume you would like to pass a parameter based on the event, so if that's the case you can do:

<a onClick={(e) => this.handleSave(e.target.value) }/></a>

Arrow functions preserve the context of this, so you don't have to use bind.

2 Comments

you don't bind this because u used arrow function. Nothing wrong with using bind this in my case.
That's why I said "I presume you would like to pass a parameter based on the event". If you shared more information about the parameter you wish to pass, the answers would be more to the point.
0
class App extends Component {
    handleSave(param){
        // doing what you need with your (param)
    }
    render() {
        return (
            <div className="App">
                <a onClick={this.handleSave.bind(this, param)} >Click Here</a>
            </div>
        );
    }
}

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.