React.Children
Children은 children과 다르다.
대문자 Children은 children prop으로 전달받은 JSX를 조작하고 변형하게 해준다.
(이 코드는 깨어지기 쉬운 코드가 될 수 있으므로 될수있는한 사용을 피하도록 한다)
Children.map(children, fn, thisArg?)
children data structure를 map하거나 각 child를 transform해 줌
import { Children } from 'react';
function RowList({ children }) {
return (
<div className="RowList">
{Children.map(children, child =>
<div className="Row">
{child}
</div>
)}
</div>
);
}
받는 인수 설명
1. children
component에 의해 받은 children prop의 값
Empty nodes, strings, numbers, React element를count 개별적 node로 count 함
Array는 못하지만 children은 할수 있다
2. fn
array map메서드의 콜백과 비슷함
첫번째 인수로 child를 부르고 두번째로는 index를 부름
이 함수에서 React node를 return 해야 함
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route index element={<Home />} />
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
</Route>
<Route element={<PageLayout />}>
<Route path="/privacy" element={<Privacy />} />
<Route path="/tos" element={<Tos />} />
</Route>
<Route path="contact-us" element={<Contact />} />
</Routes>
</BrowserRouter>
);
/teams/firebirds를 사용하려면
Outlet
중첩된 element tree는 자동적으로 렌더되지 않는다.
Routes는 첫번째 매치되는 element를 렌더링할 것이다.
여기 예에서의 다음 매치는 Teams가 될 것이다.
렌더링을 하려면 Outlet이 필요하다.
function App() {
return (
<div>
<GlobalNav />
<Outlet />
<GlobalFooter />
</div>
);
}
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
Index Routes
<Route path="teams" element={<Teams />}>
<Route path=":teamId" element={<Team />} />
<Route path="new" element={<NewTeamForm />} />
<Route index element={<LeagueStandings />} />
</Route>
여기서 경로가 만일
/teams/firebirds 이렇다면
<App>
<Teams>
<Team />
</Teams>
</App>
그러나 /teams라면
<App>
<Teams>
<LeagueStandings />
</Teams>
</App>
를 렌더링할 것
index routes는 parent routes의 path에 <Outlet>에 렌더될 것
'TIL' 카테고리의 다른 글
transpiler와 compiler의 차이 (0) | 2023.12.31 |
---|---|
Jest with Webpack (1) | 2023.12.27 |
TIL babel, AST (0) | 2023.12.23 |
TIL noop bind-event-listener memoize-one popover component classnames (0) | 2023.12.19 |
TIL: History API (0) | 2023.12.10 |