Brian H.
Brian H.

Reputation: 2235

How do I remember a React-Router URL parameter when navigating away and then back to a page?

Issue:

I have a React app that uses React-Router-DOM for hash-routing. The app has a main navigation bar with Home and About. The Home content has a sub-nav bar with A, B, and C.

When navigating to www.mysite.com/#/home/ the router defaults (redirects) to www.mysite.com/#/home/A.

When navigating from /#/about to /#/home via the Home nav-link, I want the router to remember which sub-route was last used. Currently, navigating to back to home with the Home nav link, returns to #/home/A


Example:

  1. enter URL www.mysite.com in browser ==> renders /home/#/A
  2. use sub-nav menu under Home to select B ===> renders /#/home/B
  3. use main nav menu to select About ==> renders /#/about
  4. use main nav menu to select Home ==> renders /#/home/B


Structure

<App>
    <header>
        <NavLink to="/home">home</NavLink>
        <NavLink to="/contact">contact</NavLink>
    </header>

    <section>
        <Switch>
            <Redirect exact from="/" to="/home/A" />

            <Route path="/home">
                <div>
                    <sub-header>
                        <NavLink to="/home/A">A</NavLink>
                        <NavLink to="/home/B">B</NavLink>
                        <NavLink to="/home/C">C</NavLink>
                    </sub-header>

                    <div>
                        ... content for home
                        <Switch>
                            <Route path="/home/:id" component={ChildComponentThatUsesID}>
                        </Switch>
                    </div>

                </div>
            </Route>

            <Route path="/about"> ... </Route>              

        </Switch>
    </section>
</App>

Notes

I know that I will need to change the Redirect, that is just there for convenience. I also know that I will have to change the <NavLink to="/home"> to somehow incorporate a variable property or state that will be set when using one of the sub-menu links, but I don't know how to go about doing this.

Upvotes: 4

Views: 1618

Answers (2)

user5470921
user5470921

Reputation: 576

Use react-router's internal state.

const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Redirect to={location}/>

You can access it later through this.props.location.state.

Upvotes: 0

benn98
benn98

Reputation: 125

i've never try this type of things but React Router has the history "component/props". See the documentation here : https://github.com/ReactTraining/history#properties

Upvotes: 0

Related Questions