I created a NavBar component where I have some links.
I then call this component on my App.js, so I can display the NavBar.
When I click on a link I navigate to the route but the component is not displayed.
Here is my code:
MainNavigation.js
import {
AppBar,
Toolbar,
Typography,
Button,
} from "@material-ui/core";
import React from "react";
import { Link as RouterLink } from "react-router-dom";
import { useStyles } from "./styles";
function MainNavigation() {
const classes = useStyles();
const MyApp = (
<Typography variant="h6" component="h1" button='/'>
<RouterLink to='/' className={classes.logo}>MyApp</RouterLink>
</Typography>
);
const headersData = [
{
label: "First",
href: "/first",
},
{
label: "Second",
href: "/second"
}
];
const getMenuButtons = () => {
return headersData.map(({ label, href }) => {
return (
<Button
{...{
key: label,
color: "inherit",
to: href,
component: RouterLink,
className: classes.menuButton,
}}
>
{label}
</Button>
);
});
};
const displayDesktop = () => {
return (
<Toolbar className={classes.toolbar}>
{MyApp}
<div>{getMenuButtons()}</div>
</Toolbar>
);
};
return (
<header>
<AppBar className={classes.header}>{displayDesktop()}</AppBar>
</header>
);
}
export default MainNavigation;
App.js
import './App.css';
import { Route, Routes } from 'react-router-dom';
import Second from './pages/Second';
import First from './pages/First';
import Home from './pages/Home';
import MainNavigation from './components/layout/MainNavigation';
function App() {
return (
<div>
<MainNavigation/>
<Routes>
<Route path="/" exact element={<Home />} />
<Route path="/first" element={<First />} />
<Route path="/second" element={<Second />} />
</Routes>
</div>
);
}
export default App;
Second.js
function Second() {
return <div>Second</div>;
}
export default Second
The Component is called when I click on a link because I console logged just to check. I don't know what is happening, since I don't get any errors, any clue?
CodePudding user response:
I don't see any overt issues with your routing/navigation implementation, it's working just fine...
BUT
You should be aware that the AppBar
component uses fixed positioning by default, so it actually overlays your content.
You can either use some other position value and make the app bar render with the content (probably not what you want in an app header), or you can app margin-top
to your contents to push them down below the app bar header.
Example:
h1.header {
margin-top: 5rem;
height: 200vh;
}