1

I tried to create react app using router dom and stuck in problem, i have that App component:

function App() {
    return (
        <div id="page">
            <Sidebar />
            <SearchField />
            <RouterProvider router={router} />
        </div>
    );
}

and that router config:

const router = createBrowserRouter(
    [

    {
        path: "city/:cityName",
        element: (
            <WeatherContent />
        )
    },
    {
        path: "cities",
        element: (
            <WeatherContent />
        )
    },
    {
        path: "settings",
        element: (
            <WeatherContent />
        )
    },
    {
        path: "/",
        loader: () => {
            throw redirect("city/New%20York")
        },
        element: (
            <></>
        ),
    },
    {
        path: "*",
        element: (
            <div>
                <h1>Error 404</h1>
                <h2>page not found</h2>
                <Link to="home">Go back home</Link>
            </div>
        ),
    }
]);

and my Sidebar and SearchField components have Link's from router dom, so i don't know where should i put them, so they would exist on every page and woun't throw errors, can someone help me with that?

i've tried to put path: '/' element as first, remove redirect from there and put Sidebar and SearchField inside, like that:

{
    path: "/",
    element: (
        <>
            <Sidebar />
            <SearchField />
        </>
    ),
}

but that doesn't seem to help

KoriBom
  • 15
  • 3

1 Answers1

0

You can put the Sidebar and SearchField components inside a Layout component and use <Outlet> component to render their child route elements. Also, see layout route

import "./styles.css";
import { Outlet, Link, createBrowserRouter } from "react-router-dom";

const Sidebar = () => (
  <div>
    <h1>This is sidebar</h1>
    <Link to="/cities">cities</Link>
  </div>
);
const SearchField = () => (
  <div>
    <h1>This is search field</h1>
  </div>
);

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Sidebar />
      <SearchField />
      <Outlet />
    </div>
  );
}

const routes = [
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "city/:cityName",
        element: <div>city by name</div>
      },
      {
        path: "cities",
        element: <div>cities</div>
      },
      {
        path: "settings",
        element: <div>settings</div>
      },
      {
        path: "*",
        element: (
          <div>
            <h1>Error 404</h1>
            <h2>page not found</h2>
            <Link to="home">Go back home</Link>
          </div>
        )
      }
    ]
  }
];

export const router = createBrowserRouter(routes);

codesandbox

Lin Du
  • 88,126
  • 95
  • 281
  • 483