React Router-v6

Leutbingยท2023๋…„ 5์›” 14์ผ
0

React Router Dom-v6

โ˜‘๏ธ createBrowserRouter

๋ชจ๋“  React Router ์›น ํ”„๋กœ์ ํŠธ์— ๊ถŒ์žฅ๋˜๋Š” ๋ผ์šฐํ„ฐ์ž…๋‹ˆ๋‹ค.

  • Router๋ฅผ arrayํ˜•์‹์œผ๋กœ ์ž…๋ ฅ๊ฐ€๋Šฅ

์‚ฌ์šฉ๋ฒ•

Router.jsx

const router = createBrowserRouter([
  {
    path:"/", //์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ ๊ฒฝ๋กœ
    element:<Root />,
    children : [ //ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ ๊ฒฝ๋กœ
      {
        path : "",
        element : <Home />
      },
      {
		path : "about",
        element : <About />
      }
    ]
  }
])

index.jsx
RouterProvider๋Š” router๋ผ๊ณ  ๋ถˆ๋ฆฌ์šฐ๋Š” prop์„ ๊ฐ€์ง„๋‹ค.

import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import router from './Router';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

Root.jsx

import { Outlet } from "react-router-dom";
import { Header } from "./components/Header";

function Root(){
	return(
    	<div className="App">
        	<Header />
        	<Outlet />
        </div>
    )
}

export default Root;

Outlet ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋งŒ๋“ค์–ด ์ฃผ์–ด์•ผ createBrowserRouter์—์„œ ์„ค์ •ํ•œ children์˜ต์…˜์—์„œ ์„ค์ •ํ•œ ๊ฒฝ๋กœ(path:"", path:"about")๋กœ ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋“ค์ด ๋ Œ๋”๋ง๋œ๋‹ค.

โ˜‘๏ธ errorElement

์„ค์ •ํ•œ ์ปดํฌ๋„ŒํŠธ์— ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ์™€ ์ž˜๋ชป๋œ ๊ฒฝ๋กœ๋กœ ์ ‘์†ํ•˜์—ฌ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ ์„ค์ •ํ•œ ์—๋Ÿฌ์— ๋งž์ถฐ์ง„ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค.

  • ๋‹ค๋ฅธ ๋ฉ€์ฉกํ•œ ํŽ˜์ด์ง€๊ฐ€ ์—๋Ÿฌ์˜ ์˜ํ–ฅ์„ ๋ฐ›์ง€ ์•Š๊ฒŒ ํ•ด์ค€๋‹ค.

์‚ฌ์šฉ๋ฒ•

const router = createBrowserRouter([
    {
        path:"/",
        element : <Root />,
        children : [
            {
                path:"",
                element:<Home />,
                errorElement : <ErrorComponent /> 
              //Home ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ <ErrorComponent />์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค.
            },
            {
                path:'about',
                element:<About />,
            }
        ],
        errorElement : <NotFound /> 
      // ๊ธฐ๋ณธ๊ฒฝ๋กœ์—์„œ ์ž์‹์— ํ•ด๋‹นํ•˜์ง€ ์•Š๋Š” ์ž˜๋ชป๋œ ๊ฒฝ๋กœ๋ฅผ ์ž…๋ ฅํ–ˆ์„ ๋•Œ <NotFound />์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค.
    }
])
profile
๋‹ค์‹œ ๊ฐœ๋ฐœ์„ ๋„์ „ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค!! ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป

0๊ฐœ์˜ ๋Œ“๊ธ€