Reputation: 367
I have a single page app with a 'landing page' which has its own BrowserRouter. The links on the 'landing page' route to the actual app which contains a navigation bar. The NavBar is contained inside of a separate BrowserRouter and renders to a div on the same page. I want to be able to press an image inside the navigation bar to completely reroute to the landing page. I understand in earlier versions of React, this could be done with redirect or pushing the path to the stack. However, this does not seem to work in React v4. When running the following code:
<BrowserRouter>
<div>
<ul className="NavBar">
<li>
<Route render={({ history }) => (
<img
src= {logo} height = "20"
onClick={() => { this.props.history.push('/') }}
/>
)} />
</li>
<li><NavLink exact to="/page1">Page 1</NavLink></li>
<li><NavLink to="/page2">Page 2</NavLink></li>
<li><NavLink to="/page3">Page 3</NavLink></li>
</ul>
<div className="Content">
<Route exact path="/page1" component={Page1} />
<Route path="/page2" component={Page2} />
<Route path="/page3" component={Page3} />
</div>
</div>
</BrowserRouter>
I'm getting TypeError: Cannot read property 'history' of undefined
. I've tried other methods like <Link to="/"><img/></Link>
from inside the NavBar but all of my attempts have come with other problems such as the desired link only rendering inside the child div rather than redirecting the entire page to it.
Any help is greatly appreciated.
Upvotes: 0
Views: 3495
Reputation: 577
You don't have to wrap the whole component in BrowserRouter, just the routes. Then using the Link tag will solve the problem.
<div>
<ul className="NavBar">
<li><Link to="/"><img src= {logo} height = "20" /></Link></li>
<li><Link to="/page1">Page 1</Link></li>
<li><Link to="/page2">Page 2</Link></li>
<li><Link to="/page3">Page 3</Link></li>
</ul>
</div>
<BrowserRouter>
<div>
<Route exact path="/page1" component={Page1} />
<Route path="/page2" component={Page2} />
<Route path="/page3" component={Page3} />
</div>
</BrowserRouter>
Upvotes: 1