React Router and Authentication

 To use react router in react js first we have to import react router.

1 import {createBrowserRouter} from "react-router-dom".

2 import routerProvider which is a contextapi built by react which takes router.

3 Create a constant router which contains the routes which is in an object.

4 The route consists of two parts; path and element where path is the location of the element and element is the component to be route.
Eg:

  const router = createBrowserRouter([
    {
      path: "/",
      element: <Homepage />,
    },
    {
      path: "/profilePage",
      element: <ProfilePage />,
    },
    {
      path: "/profiles",
      element: <Profiles />,
    },
  ]);

5 Then we import Link to link the component route by using the path declared in constant router.
Eg;

<Link to="/">Home</Link>

6 In react routing to link a path which is dynamic like might change depending on the property like profiles for eg we add ":"before the dynamic path.
Eg:

{ path: "/profiles/:profileId", element: <ProfilePage /> }

7 In react router we use useParams to let the component know that there are parameter in the route.
Eg:

const param = useParams();
  return (
    <div>
      <h1>Profile: {param.profileId}</h1>
    </div>

8 We use children and outlet to render the childrens component in the parent component without having to refresh the page.
Eg for children we add as:

{
      path: "/profiles",
      element: <Profiles />,
      children: [{ path: "/profiles/:profileId", element: <ProfilePage /> }],
    },

And for outlet we add the outlet tag in the component children to let it know how to render.


Comments

Popular posts from this blog

Git

REST API