0

Using react 16, react-router 4.

My domain is suppose "https://www.xyz.c". I'm having anchor tag which should redirect to "https://www.xyz.c/some-path" without reloading the page.

  1. I can implement it using <NavLink> and <Link> with to="/some-path". However, I need complete url to be shown in DOM (why? Well, on side note, I'm using itemProp for schema for which I want full path in anchor tag)
  2. Implementing it with <a> and props.history tag like following causes to again replace with relative url, i.e. it becomes https://www.xyz.c/https://www.xyz.c/some-path in the url.
<a data-url="https://www.xyz.c/some-path" onClick={this.onClick}>Label</a>

onClick = e => {
  e.preventDefault();
  this.props.history.push(urlFromDataSet);
}

This seems impossible with <Navlink>, <Link> or <a> + props.history, since the policy is that history.replace, or history.push works on url with same origin. My url is also of same origin, however, I'm giving full path in href.

However, facebook is achieving the same in its header (Check on FB by going to home page, once loaded completely, then Click on your own profile button in header. It doesn't reload the page.)

How can we do that?

1 Answer 1

1

You are half there, you can use URL API to get the pathname of your data-url attribute then push it.

const url = new URL(dataUrl) 
this.props.history.push(url.pathname)

More information about URL API: https://developer.mozilla.org/en-US/docs/Web/API/URL

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

1 Comment

Nice solution. IE 11 doesn't support URL though.

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.