5

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.

2
  • 3
    Value of onClick is incorrect. You must define it like this: onClick={() => this.saveData(post.title)} Commented Nov 22, 2018 at 8:33
  • thanks, it worked. Commented Nov 22, 2018 at 8:35

1 Answer 1

10

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.

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

9 Comments

Hi, I tried it works. But thanks for your answer. But please tell me, how can i redirect user after my function work done to the same url?
your code is not working. I applied alert in the given function and the alert is showing without clicking on link.
I am saying, the function is calling without click on link. alert is showing when i refresh page where link to next page exists.
You mean, I need to put "More" Link text in span?
Not working. alert is again calling at render. I updated my answer. You can see that what i am using.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.