user10298495
user10298495

Reputation:

Call function on click of link in react js

I am using react property instead of tag. So what i need to do is to call a function on click of link.What approach should i need to follow to achieve this.can i use the below function.

<Link to={`/testimonial/${post.id}`} className="red">
  <span onClick={this.saveData(post.title)}>More</span>
</Link>

I have to trigger the function, that will save data to localStorage and then redirect user to the component.

Thanks.

Upvotes: 5

Views: 19426

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Yes. You can use event handlers in <Link />. Or, you may even bind the event handler in the child or parent element if you want to have more control. Both are successive:

<Link to={`/component/${post.id}`}/>
  <span onClick={this.saveDataToLocalStorage}>More</span>
</Link>

Alternaively, you may avoid using <Link /> and use normal element as you want:

<span onClick={this.saveDataToLocalStorage(post.id)}>More</span>

And inside the function, you may redirect to the path:

saveDataToLocalStorage(postId) {
this.props.history.push(`/component/${postId}`)

This way, you'll have more control, you can log, alert etc. and when you wish redirect to the page.

Upvotes: 10

Related Questions