James Ives
James Ives

Reputation: 3365

<Link> onClick is causing my page to refresh

I have a navigation bar on my site that fires off a function passed in from props when they are clicked, like so:

<Filter 
  filter={this.props.params.filter}
  sub={this.props.params.sub}
  search={this.props.location.search}
  fetchData={() => this.fetchData}  />

Filter Component:

<Link to={`/r/${this.props.sub}/new/${this.props.search}`} onClick={this.props.fetchData()}>
 <span className="mdl-tabs__tab is-active">New</span>
</Link>
<Link to={`/r/${this.props.sub}/rising/${this.props.search}`} onClick={this.props.fetchData()}>
 <span className="mdl-tabs__tab is-active">Rising</span>
</Link>

Fetch Data:

      fetchData() {
        if (this.props.params.sub) {
          if (this.props.params.filter) {
              let query = `${this.props.params.sub}/${this.props.params.filter}`;

              this.props.fetchList(query, this.props.location.search);
          }
      }
    }

The problem I'm having is that whenever one of these link tags is clicked it refreshes the entire page. While this works I'd prefer the page didn't refresh. Where am I going wrong here?

Upvotes: 1

Views: 2908

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

So you have the answer and, maybe, that can help others: you forgot to bind the event handler in the component's constructor.

export default YourComponent extends Component {
  constructor(props) {
    super(props)

    this.fetchData = this.fetchData.bind(this)
  }

  fetchData() {
    ...
  }

  render() {
    return (
      ...
      <Link
        to={`/r/${this.props.sub}/new/${this.props.search}`}
        onClick={this.fetchData}
      >
        <span className="mdl-tabs__tab is-active">New</span>
      </Link>
    )

  }
}

Upvotes: 2

Related Questions