あさた研メモ

主に私が気づいたこととか困った時のメモとか書き留めとく用。

react-router v4 でホームディレクトリだけを表示したい

概要

react-router で ルーティングをする際、ホームディレクトリ("/")だけを表示したいのに、他のページ("/hoge")なども一緒に描画される

解決策

ホームディレクトリ("/")のRouteのプロパティに exact={true} を入れる

class App extends React.Component {
  public handleState(item: number) {
    this.setState({item});
  }

  public content() {
    return (
      <div>
        <Route
          exact={true}
          path="/"
          render={props => <Top handleState={this.handleState} />}
        />
        <Route path="/hoge" component={Hoge} />
        <Route path="/fuga" component={Fuga} />
      </div>
    );
  }

  public render() {
    return (
      <BrowserRouter>
        {this.content()}
      </BrowserRouter>
    );
  }
}