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?

1

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

Comments

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.