DEV Community

"Rocky" Hiroki Ueno
"Rocky" Hiroki Ueno

Posted 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 { BrowserRouter, Route, Routes, Link } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <header>header</header>
      <BrowserRouter>
        <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.

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)