220321 TIL

leevshan·2022년 3월 21일
0

React

JSX elements are compiled into pure javascript using Babel.

react-router-dom

Install by npm i react-router-dom
This package makes it easier for a react project to be a SPA.

Using react-router-dom v6
Unlike previous versions, from v6 one should code a routes-system like

<BrowserRouter>
      <Routes> {/*This tag is needed */}
        <Route path="/" element={<Home />} /> {/* 'component' props is replaced with 'element' */}
        <Route path="/profile" element={<Profile />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </BrowserRouter>

'exact' props is not needed anymore.

Reading URL props

If someone wants a 'dynamic routing' using id(e.g. profileId), one can nest another route in original route.

<Route path="/profile" element={<Profile />} >
  <Route path=":profileId" element={<Profile />} />
</Route>

Then in the Profile component, use useParams() function.

import { useParams } from "react-router-dom";

export default function Profile() {
  const params = useParams();
  const id = params.profileId;
  console.log(id);
  return (
    <div>
      <h2>Profile 페이지입니다.</h2>
      {id && <p>id는 {id}입니다.</p>}
    </div>
  );
}
profile
Planby 개발자

0개의 댓글