React/Router

React - Router Switch & NotFound Component

고코모옹 2021. 6. 5. 19:21
  • Switch Component
    • 여러 Route 중 순서대로 일치하는 하나만 노출시킴
    • exact를 뺄 수 있는 로직 구현 가능
    • 가장 마지막에 어떠한 path도 일치하지 않으면 보여주는 Not Found 컴포넌트 설정
    • 범위가 가장 작은 컴포넌트를 위에 배치
// App.js
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';
import Profile from './pages/Profile';
import NotFound from './pages/NotFound';

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/profile/:id" component={Profile} />
        <Route path="/profile" component={Profile} />
        <Route path="/about" component={About} />
        <Route path="/" exact component={Home} />
        <Route component={NotFound} />
      </Switch>
    </BrowserRouter>
  );
}