ahmedskulj10
ahmedskulj10

Reputation: 421

How to apply certain layout through out whole app using react router?

Like the title says, I want to implement a certain layout throughout the whole app, but that layout should persist with every route. This is how my routes are implemented:

const routes = [
  {
    path: "/",
    component: "",
    exact: true,
  },
  {
    path: "/messagelist",
    component: "",
    exact: true,
  },
  {
    path: "/ceostats",
    component: "",
    exact: true,
  },
  {
    path: "/categories",
    component: "",
    exact: true,
  },
  {
    path: "/ubcategories",
    component: "",
    exact: true,
  },
  {
    path: "/resources",
    component: "",
    exact: true,
  },
  {
    path: "/surveys",
    component: "",
    exact: true,
  },
  {
    path: "/users",
    component: Users,
    exact: true,
  },
  {
    path: "/usergroups",
    component: "",
    exact: true,
  },
  {
    path: "/users/new",
    component: User,
    exact: true,
  },
  {
    path: "/users/:id",
    component: User,
    exact: true,
  },
];

This is the Route.js component where I store all my routes.

function RouterProvider() {
  return (
    <Switch>
      {routes.map((route, index) => (
        <Route
          path={route.path}
          component={route.component}
          exact={route.exact}
          key={index}
        />
      ))}
    </Switch>
  );
}

This is RouteProvider.js, this is where I do the routing.

const Layout = ({ title, hasSearchBox, children, searchValue, onChange }) => {
  return (
    <LayoutContainer>
      <TopLayoutContainer>
        <Title>{title}</Title>
        {hasSearchBox ? (
          <Searchbox value={searchValue} onChange={onChange} />
        ) : (
          ""
        )}
      </TopLayoutContainer>
      {children}
    </LayoutContainer>
  );
};

And this is Layout.js, the layout I want to have throughout the whole app. Now I am manually importing this component in every other component where I want to have this layout. If anyone knows any way I can have this Layout only in one place, and then dynamically change these props, such as title, etc. so it fits the component that needs this layout.

Upvotes: 1

Views: 670

Answers (1)

Jai248
Jai248

Reputation: 1649

You just need to add your layout in your parent component like this and it will apply to your every page

import { useLocation } from 'react-router-dom';

function RouterProvider() {
  let location = useLocation();
  console.log(location.pathname);
  return (
   <MyLayout>
    <Switch>
      {routes.map((route, index) => (
        <Route
          path={route.path}
          component={route.component}
          exact={route.exact}
          key={index}
        />
      ))}
    </Switch>
  </MyLayout>
  );
}

Upvotes: 1

Related Questions