2

I have a "settings" page in my react app. The page has several tabs rendering different parts of settings.

It would be better UX if a user can share urls with other users.

What I want is (inside "settings" page):

  1. user A clicks a tab
  2. url changes with a #tabname appended
  3. user A send that url to user B, and user B open that url
  4. user B sees the same tab as user A

But with react router, the whole page re-renders if the url changed:

import { withRouter } from "react-router-dom"

const MyComp = (props) => {
  ...

  const onTabChange = () => {
    // append #tabname here
    props.history.replace(...); // or `push`
    ...
  }

  ...

export default withRouter(MyComp)
}

After a lot of searches, I found a solution to use window.history:

  const onTabChange = () => {
    window.history.pushState(null, null, "#tabname");
    ...
  }

This does the trick, but little information and explanation, and I'd love to know the consequences of using this trick.

Is this a valid solution (for a react app)? Will this cause any problem?

(PS. I know how to parse a url)


More details:

To be more specific, there is a AuthChecker wrapper for all pages. When react router's location changes, it checks for the route's allowed auths and current user's auth.

I've tried /path/:id and everything but all change location, so auth checked and page rerendered.

And I've given up a solution in react router and just want to know: is it safe to change url with window.history in a react app using react router to manage routes?

CSSer
  • 2,131
  • 2
  • 18
  • 37
  • 2
    Does this answer your question? [URL change without re rendering in React router](https://stackoverflow.com/questions/56053810/url-change-without-re-rendering-in-react-router) – idmean Jan 26 '21 at 09:01

1 Answers1

1

this question is already answerd at this post.

so it says window has a property called history and there is a method on history which helps you update the history state without react-router-dom understanding it.

like this:

window.history.replaceState(null, 'New Page Title', '/new_url');
DevAddict
  • 1,583
  • 1
  • 10
  • 17