Reputation: 256
I'm having a hard time understanding how Routes work in React. Right now I have my App.js with my routes for different pages like
<Router>
<Switch>
<Route path="/" component={Index} />
<Route path="/create" component={Create} />
<Route path="/view/:id" component={View} />
<Route path="/edit/:id" component={Edit} />
</Switch>
</Route>
All the routes work fine on this. My view page layout looks something like this.
--------------------------------------------------------------------------------------------
NAVIGATION | HOME | ABOUT
--------------------------------------------------------------------------------------------
|Side bar |
| |
|Option 1 | Content that changes based on sidebar option
|Option 2 |
| |
Here the navigation bar and the side bar will always remain the same but the content changes based on the option selected in the sidebar. To do so I made my view like
<Container>
<Row>
<Col>
<Sidebar />
</Col>
<Col>
<Router>
<Switch>
<Route path="/option1" component={Option1} />
<Route path="/option2" component={Option2} />
</Switch>
<Router>
</Col>
</Row>
</Container>
I assumed this would replace the content section with the Option components but it doesn't seem to work like that. Is there something I'm missing? I did try adding the routes to App.js which works fine but it won't load the <Sidebar />
component. I guess I could load the sidebar in each view but that defeats the purpose of React. I'm very to new to React so any help is appreciated.
Upvotes: 1
Views: 413
Reputation: 19119
To access the route somewhere in your application:
Import Link
(or NavLink
if necessary) from react-router-dom
.
Use it:
<Link to="/create">Create</Link>
I've set up a working CodeSandbox demo for you which is doing what you want.dex.
Basic structure:
index.js — create `BrowserRouter wrapper
import { BrowserRouter } from "react-router-dom";
<BrowserRouter>
<App />
</BrowserRouter>,
App.js — Sets up basic structure.
<div className="App">
<Sidebar />
<Main />
</div>
Main.js — Establish routing logic
<main>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/create" component={Create} />
<Route exact path="/destroy" component={Destroy} />
</Switch>
</main>
Sidebar.js — Access the route
<aside>
<nav aria-label="main navigation">
<Link to="/">Home</Link>
<Link to="/create">Create</Link>
<Link to="/destroy">Destroy</Link>
</nav>
</aside>
Upvotes: 1