I am new to MUI and React. I copied the code from the example "App Bar with responsive menu" from MUI.com into js file.Then called it with in the at App.js. A menu appears. In the example code there are four handler functions are there. The setAnchorEInav, setAnchorEIuser are used. My need is if I click Product Menu Item it should go to the url "/product". How to do that? Any help will be grateful for me take next step in my learning the MUI and React.
CodePudding user response:
You will need to use something like react router
https://v5.reactrouter.com/web/guides/quick-start
You will need to define the routes of your react app like in this example
<Router>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
After you have defined your routes on your app bar you can make use the link component to move between pages:
<Link to="/users">Users</Link>
CodePudding user response:
Dave is correct in saying you need to use React Router for navigation. Nothing wrong with their answer, I just wanted to include that React Router v6 has been released and adds a more modern and simplified outlet-based routing mechanic.
https://reactrouter.com/docs/en/v6/getting-started/overview
Declare your routes at the top level of your project (App.js)
<Router>
<Routes>
<Route path='/' element={<Dashboard />}>
<Route element={<HomePage />} path='home' />
<Route element={<UsersPage />} path='users'>
<Route element={<AllUsers />} index /> // 'website.com/users'
<Route element={<AddUser />} path='add-user'/> //'website.com/users/add-user'
<Route element={<ViewUser /> path=':id' /> //'website.com/users/012345'
</Route>
<Route element={<AboutPage />} path='about' />
</Route>
</Routes>
</Router>
Dashboard.js
const Dashboard = () => {
return (
<div>
<Outlet />
</div>
}
Base dashboard pages
const UsersPage = () => {
return (
<div>
<Outlet />
</div>
}
const HomePage = () => {
return (
<div>
<Outlet />
</div>
}
const AboutPage = () => {
return (
<div>
<Outlet />
</div>
}