DEV Community

nick-raym
nick-raym

Posted on

Routing in React

Routing refers to the process of navigating between different pages without triggering a full page reload. It allows coders to create dynamic elements in a page, while keeping components that you want in every page like a nav bar or a footer. here is an example of routing:

const router = createBrowserRouter([
  {
    path:"/",
    element: <Root/>,
    children:[
      {
        path:"/",
        element: <Welcome/>
      },
      {
      path: "/about",
      element:<About/>
    },
  {
    path:"tea",
    element:<Teas/>
  }]
  }

])

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router}/>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

In this file we are defining what the url paths look like and what to components(elements) to show when we go to that url. For example the opening page will provide the element signified by the "/" path, while the /about will show the component when directed to that url. In our root file we define what is static (our Nav bar) throughout the pages and what will change with the component,

import Nav from "../nav"
import { Outlet } from "react-router-dom";
export default function Root() {
  return (
    <div>
      <Nav />
      <Outlet />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)