Reputation: 144
I am quite new to ReactJS and its routing principles, have tried solving this issue myself but with no success and I am starting to wonder if it is possible to accomplish my idea.
I have an app like this :
<App>
<Navbar />
<MainContainer/>
</App>
Navbar :
<Navbar>
<ul>
<li>My Account</li>
<li>Settings</li>
.......
</ul>
</Navbar>
Is there any possible way to change contents of MainContainer from Navbar ul option?
Upvotes: 0
Views: 79
Reputation: 683
You need to start off by adding a routing library such as react-router-dom which is one of the most popular ones.
npm i react-router-dom
You can read more about it here.
Now that you have the library, you can import the following in the App.tsx file (or in the file that you posted here) at the top:
import { Switch, Router, BrowserRouter } from "react-router-dom";
Those are one of the basics use of the routing library, but if we now would keep going with your file, then it would end up looking something like this:
<BrowserRouter>
<App>
<Navbar />
<MainContainer>
<Route />
<Switch>
<Route exact path="/my-acount" component={() => <MyAccount />} />
<Route exact path="/settings" component={() => <Settings />} />
</Switch>
</MainContainer>
</App>
</BrowserRouter>
In this case, your Navigation bar would look something like these:
<Navbar>
<ul>
<li><a href="/my-account">My Account</a></li>
<li><a href="/settings">Settings</a></li>
.......
</ul>
</Navbar>
And you might saw the <MyAccount />
and <Settings />
component inside
<Route exact path="link" component={() => ...} />
but the main goal is to put in the component (or function) you want to show when the user is redirected to that path. It can also be something like:
<Route exact path="/my-account" component={() => return (<p>My Account</p>)}
And a good feature to top it of with is the feature of sending the user to the top of the page when going to a new link/page. For that, you can add the following function inside <Route/>
so that it results in something like this:
const scrollToTop = () => {
window.scrollTo(0, 0);
return null;
};
return (
<BrowserRouter>
<App>
<Navbar />
<MainContainer>
<Route component={scrollToTop} /> {/* <-- here */}
<Switch>
<Route exact path="/my-acount" component={() => <MyAccount />} />
<Route exact path="/settings" component={() => <Settings />} />
</Switch>
</MainContainer>
</App>
</BrowserRouter>
);
Upvotes: 1
Reputation: 332
Take a look at this: React router nav bar example
I think it may be what you're looking for: it uses react-router, the most popular React routing library.
Upvotes: 0