DEV Community

"Rocky" Hiroki Ueno
"Rocky" Hiroki Ueno

Posted on • Updated on

React Rooting (react-router-dom)

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

src/Pages/About.js

import React from "react";

const About = () => {
  return (
    <div>
      <h1>About</h1>
    </div>
  )
}
export default About;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Here set the rooting.
"path" is URL, "element" is a page to call with the URL.

Top comments (0)