Here is how to set rooting in React app using react-router-dom.
I will set rooting in App.js.
Install react-router-dom
npm install react-router-dom
Make pages App.js will call
src/Pages/Home.js
import React from "react";
const Home = () => {
return (
<div>
<h1>Home</h1>
</div>
)
}
export default Home;
src/Pages/About.js
import React from "react";
const About = () => {
return (
<div>
<h1>About</h1>
</div>
)
}
export default About;
Set rooting in App.js
src/App.js
import './App.css';
import Home from "./Pages/Home";
import About from './Pages/About';
import Header from './Components/Header';
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";
function App() {
return (
<div className="App">
<BrowserRouter>
<Header />
<Link to="/">Home</Link> | <Link to="/about">About</Link>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
Finally, I can call Home.js and About.js from App.js.
*Header needs to be assigned in BrowserRouter to insert Link into Header.
Tips
import { BrowserRouter, Route, Routes, Link } from "react-router-dom";
Here App.js import react-router-dom and can use it.
<BrowserRouter>
<Link to="/">Home</Link> | <Link to="/about">About</Link>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</BrowserRouter>
Here set the rooting.
"path" is URL, "element" is a page to call with the URL.
Top comments (0)