React Router 6

Happhee·2021년 12월 28일
1

💙  React 💙

목록 보기
9/18
post-thumbnail

React Router의 변경사항을 알아보자.

  • Rich Router와의 통합을 진행하였다.

  • Remix

  • Link to -> Route path

  • Switch -> Routes

  • render -> element


🖥 Routes

  • exact 삭제

  • path="/user/:id" -> path=":id" 상대경로```로 지정

  • 여러 라우팅을 매칭하고 싶으면 *을 사용

  • V6

import {BrowserRouter, Routes, Route, Link } from 'react-router-dom';

function App(){
  return (
    <BrowserRouter>
    	<Routes>
			<Route path="/" element ={<Home />}/>
			<Route path ="user/*" element={<Users />} />
    	</Routes>
    </BrowserRouter>
  );
}

function Users(){
	return (
    	<div>
      		<nav>
      			<Link to="me">My Profile</Link>
      		</nav>
      		<Routes>
      			<Route path=":id" element={<UserProfile />} />
				<Route path="me" element={<OwnUserProfile />} />
      		</Routes>
      	</div>
    )
}

🖥 중첩 라우팅

📍 중접라우터에서 Outlet 컴포넌트 사용

// Router.js

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import User from "../Pages/User";
import UserProfile from "../Pages/UserProfile";

const Router = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="user/*" element={<User />}>
          <Route path=":id" element={<UserProfile />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
};

export default Router;
// User.js

import React from "react";
import { Link, Routes, Route, Outlet } from "react-router-dom";
import UserProfile from "./UserProfile";

const User = () => {
  return (
    <div>
      <h1>This is Web</h1>
      <ul>
        <li>
          <Link to="1">Post #1</Link>
        </li>
        <li>
          <Link to="2">Post #2</Link>
        </li>
        <li>
          <Link to="3">Post #3</Link>
        </li>
        <li>
          <Link to="4">Post #4</Link>
        </li>
    </ul>
      //핵심!!!!!!!!!!!!!!!!!!!!!!!!!!!
      <Outlet />
    </div>
  );
};

export default User;


// --------------------------------------------------------------------------------
// UserProfile.js

import React from "react";

const UserProfile = () => {
  return <div>This is UserProfile</div>;
};

export default UserProfile;

📍 바로 컴포넌트사용

// Router.js

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import User from "../Pages/User";
import UserProfile from "../Pages/UserProfile";

const Router = () => {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="user/*" element={<User />}>
    	</Routes>
    </BrowserRouter>
  );
};

export default Router;
// User.js

import React from "react";
import { Link, Routes, Route } from "react-router-dom";
import UserProfile from "./UserProfile";

const User = () => {
  return (
    <div>
      <h1>This is Web</h1>
      <ul>
        <li>
          <Link to="1">Post #1</Link>
        </li>
        <li>
          <Link to="2">Post #2</Link>
        </li>
        <li>
          <Link to="3">Post #3</Link>
        </li>
        <li>
          <Link to="4">Post #4</Link>
        </li>
    </ul>
      //핵심!!!!!!!!!!!!!!!!!!!!!!!!!!!
    	<Routes>
      		<Route path=":id" element={<UserProfile />} />
        </Routes>
    </div>
  );
};

export default User;


// --------------------------------------------------------------------------------
// UserProfile.js

import React from "react";

const UserProfile = () => {
  return <div>This is UserProfile</div>;
};

export default UserProfile;

🖥 useLocation(), useNavigate()

  • v5.js
<Route path=":userId" component={Profile}/>
<Route path=":userId" render={routeProps => (
                              <Profile routeProps={routeProps}
								animate={true}/>)}/>
<Route path=":userId" children={({ match }) => (
    match ? (
      <Profile match={match} animate={true} />
    ) : (
      <NotFound />
    )
  )}
/>
  • v6
<Route path=":userId" element={<Profile />} />
<Route path=":userId" element={<Profile animate={true}/>} />


function Profile({animate})(
  let params = useParams();
  let location = useLocation():
  let navigation = useNavigation();
)
  • useHistory가 useNavigate으로 변경

  • v6.js

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

function App(){
	let navigate = useNavigate();
  	function handleClick(){
    	navigate("/home");
    }
  
  	return(
    	<div>
      		<button onClick={handleClick}>go home</button>
			<button onClick={()=> navigate(-2)}>go 2 pages back </button>
			<button onClick={()=> navigate(1)}> go forward</button>
      	</div>
    )
}

🖥 Route path의 patterns

/groups
/groups/admin
/user/:id
/user/:id/message
/file/*
/file/:id/*

🖥 Link to의 . 옵션

  • 상대경로로 표시가 가능해졌다
function App(){
	return(
    	<Routes>
      		<Route path="users" >
      			<Route path =":id/message"
      				element={
      					<Link to=".."/>}/>
						// /users
      		</Route>
      	</Routes>
    )
}
profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글