Routing in React

nickraym

nick-raym

Posted on February 8, 2024

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
💖 💪 🙅 🚩
nickraym
nick-raym

Posted on February 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024