0

I have an onClick handler that is bound to currentAreas component. The onClick handler is called simultaneously when the currentAreas component is called, but does not work after that.

onClick does not work when I try to click the anchor tag and I think it might be due to the way I'm binding the onClick function.

currentAreas.js

import React, { Component, PropTypes } from 'react';

export default class currentAreas extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { onClick } = this.props;

    return(
        <div className="list-group panel">
          <a href="#demo3" className="list-group-item" onClick={onClick("All", "All")} >All</a>

        </div>
    );
  }
}

currentList.js (Main component)

class currentList extends Component {
    constructor(props) {
      super(props);

      this.updateLocation = this.updateLocation.bind(this);
    }

  updateLocation(name, nameLocation){
    console.log(name);
    console.log(nameLocation);
  }

    render() {
        return (
           <div className="step-3-container">

            <CurrentAreas 
              onClick ={this.updateLocation} />
        </div>
      )
    }
  }

2 Answers 2

3

Whenever your javascript interpreter "sees" a "()" it tries to execute the function that is before "()". Therefore, what your code is actually doing is executing onClick (the one that came from props), passing as arguments "All" and "All". So, what you need to do is, instead of calling it yourself, let the onClick handler call it.

In other words, the onClick prop must receive a function.

One possible solution is to wrap your onClick into an arrow function, doing something like that:

<a href="#demo3" onClick={() => onClick("All", "All")}>All</a>

Or, you may bind the parameters to your function (bind returns a function, so it will fit well on onClick).

<a href="#demo3" onClick={onClick.bind(null, "All", "All")}>All</a>

The first bind parameter is the this value inside the binded function.

FMI about bind: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

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

Comments

2

Youre executing the function during the declaration of the component, which likely means youre triggering it on render, not click

onClick={onClick("All", "All")}

needs to be

onClick={onClick.bind(null, "All", "All")}

or

onClick={function(){ onClick("All", "All"); }}

The onClick of a react component needs a callback that can be executed. you are passing in the return value of this.props.onClick because youre calling it right away with arguments

Comments

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.