728x90
문제
<Router>
<Switch>
<Route path="/login">
{user ? <Redirect to="/" /> : <Login />}
</Route>
<Topbar />
<div className="container">
<Sidebar />
<Route exact path="/">
<Home />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/user/:id">
<User />
</Route>
<Route path="/newUser">
<NewUser />
</Route>
<Route path="/movies">
<ProductList />
</Route>
<Route path="/product/:productsId">
<Product />
</Route>
<Route path="/newproduct">
<NewProduct />
</Route>
</div>
</Switch>
</Router>
로그인 페이지가 Topbar 컴포넌트의 영향을 받지 않도록 Login을 따로 빼주고,
그 아래에 Topbar와 나머지 컴포넌트를 묶은 div를 배치했을 때,
어떻게해도 Topbar를 제외한 나머지가 보이지 않는 문제가 있었습니다.

해결방법
찾아본 결과, Switch는 바로 아래에 있는 first-level의 컴포넌트만을 위해 작동하며 전체 트리를 순회하지 않기 때문에
나머지가 보이지 않았습니다.
따라서 React fragment를 사용해서 하나로 묶어준 결과 제대로 작동하는 것을 볼 수 있었습니다.
<Router>
<Switch>
<Route path="/login">
{user ? <Redirect to="/" /> : <Login />}
</Route>
{user && (
<>
<Topbar />
<div className="container">
<Sidebar />
<Route exact path="/">
<Home />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/user/:id">
<User />
</Route>
<Route path="/newUser">
<NewUser />
</Route>
<Route path="/movies">
<ProductList />
</Route>
<Route path="/product/:productsId">
<Product />
</Route>
<Route path="/newproduct">
<NewProduct />
</Route>
</div>
</>
)}
</Switch>
</Router>

728x90
'React' 카테고리의 다른 글
| React - useReducer Hook에 대해 (0) | 2022.08.19 |
|---|---|
| React - nextjs 사용 시 Parsing error : Cannot find module 'next/babel' 오류 해결방법 (0) | 2021.11.13 |
| React - useEffect 사용 시 array를 dependency로 사용했을 시 나타나는 경고 (0) | 2021.09.16 |