I have created a website as a learning project for React learning. I want to navigate from one component to another component whenever I click on the Navbar buttons.
for example, if someone click on contact they needs to navigate to the below contact information as shown in the image.
Navbar is one component and contact is another component. Both are in different path also.
Let me know if any other information you need from my side.
//This is NavBar component location src/component/Contact.js
import classes from "./NavBar.module.css";
import { Link, Router } from "react-router-dom";
const NavBar = (props) => {
return (
<div className={classes.navbar}>
<li className={classes.li}>
<Link className={classes.a} to={"/Contact"}>
Contact
</Link>
</li>
</div>
);
};
export default NavBar;
//This is Contact component location src/component/Contact.js
import classes from "./Contact.module.css";
import { Router, Route } from "react-router-dom";
function Contact() {
return (
<footer>
<div className={classes.contact}>
<p>Contact Me</p>
</div>
</footer>
);
}
export default Contact;
//This is App Component Location src/UI/App.js
import NavBar from "./components/NavBar";
import Contact from "./components/Contact";
import classes from "./App.module.css";
import { Router, Route } from "react-router";
function App() {
return (
<div className={classes.appcontrol}>
<NavBar />
<Route path="/Contact">
<Contact />
</Route>
</div>
);
}
export default App;`
You need only one single Router component wrapping your app to provide the routing context. Remove the routers wrapping the NavBar and Contact components, add one around both in App, or wrap App itself where it's rendered.
You can render Contact into a Route in App.
NavBar
const NavBar = (props) => {
return (
<div className={classes.navbar}>
<li className={classes.li}>
<Link className={classes.a} to={"/contact"}>
Contact
</Link>
</li>
</div>
);
};
Contact
function Contact() {
return (
<footer>
<div className={classes.contact}>
<p>Contact Me</p>
</div>
</footer>
);
}
App
import NavBar from "./components/NavBar";
import Contact from "./components/Contact";
import classes from "./App.module.css";
import { BrowserRouter as Router, Route } from "react-router-dom";
function App() {
return (
<Router>
<div className={classes.appcontrol}>
<NavBar />
<Route path="/contact">
<Contact />
</Route>
</div>
</Router>
);
}