Reputation: 2235
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
/home/#/A
Home
to select B
===> renders /#/home/B
About
==> renders /#/about
Home
==> renders /#/home/B
<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>
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
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
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