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.

1 Answers1

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • 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? –  Nov 22 '18 at 08:02
  • your code is not working. I applied alert in the given function and the alert is showing without clicking on link. –  Nov 22 '18 at 08:11
  • I am saying, the function is calling without click on link. alert is showing when i refresh page where link to next page exists. –  Nov 22 '18 at 08:23
  • You mean, I need to put "More" Link text in span? –  Nov 22 '18 at 08:25
  • Not working. alert is again calling at render. I updated my answer. You can see that what i am using. –  Nov 22 '18 at 08:28
  • No, on same page. where i have links to redirect to another page. –  Nov 22 '18 at 08:30
  • alert is again calling on render, without clicking on link. –  Nov 22 '18 at 08:31
  • I bind it in constructor like this: this.saveData = this.saveData.bind(this) so why i need to bind it again? –  Nov 22 '18 at 08:36
  • then there might another issue. it might help: https://stackoverflow.com/questions/52788613/react-js-the-most-efficient-way-to-pass-a-parameter-to-an-event-handler-without/52788901#52788901 – Bhojendra Rauniyar Nov 22 '18 at 08:38