Reputation: 45
I have an App component, that has child component NavigationBar. That NavigationBar also has children, those are NavigationBarTabs. What I want to do, is to manage routing in App component, but have links in NavigationBarTabs. If I do it this way, I can only get new content in App by refreshing. If I keep links in App component it works fine, but obviously I would like those links to be in NavigationBarTabs. Is there any way I can do that? Examples below:
Works after clicking link:
<BrowserRouter>
<Route path ='/Profile' component = {Profile}/>
<Route path ='/About' component={About}/>
<Route path ='/Catalog' component={Catalog}/>
<Link to={'/Profile'}>Profile</Link>
<Link to={'/Catalog'}>Catalog</Link>
<Link to={'/About'}>About</Link>
</BrowserRouter>
Works after clicking link and refreshing page:
<BrowserRouter>
<NavigationBar/> <--- Tabs with Links are stored there, same 'to' prop
<Route path ='/Profile' component = {Profile}/>
<Route path ='/About' component={About}/>
<Route path ='/Catalog' component={Catalog}/>
</BrowserRouter>
Upvotes: 2
Views: 274
Reputation: 99
I had a similar issue where I wanted my links to be in a sliding side bar. here is a way I found worked for me.
Routes Component: I imported the components which i would like to route to into my routes component. As below.
import React, {Component} from 'react'
import {BrowserRouter, Route, Link} from 'react-router-dom';
import Component from './component.js';
const routes = [
{
path: '/',
exact: true,
main: () => <place component here/>
},
{
path: '/dogs',
main: () => <place component here/>
},
{
path: '/cats',
main: () => <place component here/>
}
];
export default routes;
Sidebar Component: I then placed my links in my sidebar component as below.
import React from 'react';
import './SideDrawer.css';
import {BrowserRouter, Route, Link} from 'react-router-dom';
const sideDrawer extends Component{
render(){
return(
<nav className='sidebar'>
<ul>
<li><Link to='/'>Home</Link></li>
<li><Link to='/dogs'>Dogs</Link></li>
<li><Link to='/cats'>Cats</Link></li>
</ul>
</nav>
);
}
};
export default sideDrawer;
Then in my App.js component which will render my page I made the following imports:
import React, {Component} from 'react';
import SideDrawer from './components/SideDrawer/SideDrawer';
import {BrowserRouter, Route, Link} from 'react-router-dom';
import routes from './components/routes/routes.js';
Then included the following in my return statement.
return(
<div style={{height:'100%'}}>
<BrowserRouter>
<SideDrawer/>
<main>
{routes.map((route) => (
<Route
key={route.path}
path={route.path}
exact={route.exact}
component={route.main}
/>
))}
</main>
</BrowserRouter>
</div>
);
}
}
please note everything inside the App.js return statement is wrapped inside a BrowserRouter tag. Hope this can help you.
Upvotes: 0