React-Router: Switch

Contents

GitHub Repos

💾 Ncoughlin: React-Streams-Client

💾 Ncoughlin: React-Streams-API

Intro

We will continue here working on our Twitch Clone Project called ”🏷️ Glitch“.

The React-Router switch is fairly simple. It wraps a set of routes and makes it so that there is only one correct match for each of them. This makes it so that a wildcard route will not also match on an exactly defined route.

Let us take the following set of routes as an example.

App.js
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import Header from "./Header";
import StreamList from "./streams/StreamList";
import StreamCreate from "./streams/StreamCreate";
import StreamDelete from "./streams/StreamDelete";
import StreamEdit from "./streams/StreamEdit";
import StreamShow from "./streams/StreamShow";

class App extends Component {
  render() {
    return (
      <div className="ui container">
        <BrowserRouter>
          <Header />
            <Route path="/" exact component={StreamList} />
            <Route path="/streams/new" exact component={StreamCreate} />            <Route path="/streams/:id/delete" exact component={StreamDelete} />
            <Route path="/streams/:id/edit" exact component={StreamEdit} />
            <Route path="/streams/:id" exact component={StreamShow} />        </BrowserRouter>
      </div>
    );
  }
}

export default App;

If you look at the two highlighted routes we can see that /streams/new could actually be a match for /streams/:id. Which gives us the following issue when we navigate to the new stream route.

StreamShow component is showing

Our StreamShow component is showing.

However we can just wrap our routes in a switch.

App.js
import React, { Component } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";

import Header from "./Header";
import StreamList from "./streams/StreamList";
import StreamCreate from "./streams/StreamCreate";
import StreamDelete from "./streams/StreamDelete";
import StreamEdit from "./streams/StreamEdit";
import StreamShow from "./streams/StreamShow";

class App extends Component {
  render() {
    return (
      <div className="ui container">
        <BrowserRouter>
          <Header />
          <Switch>
            <Route path="/" exact component={StreamList} />
            <Route path="/streams/new" exact component={StreamCreate} />
            <Route path="/streams/:id/delete" exact component={StreamDelete} />
            <Route path="/streams/:id/edit" exact component={StreamEdit} />
            <Route path="/streams/:id" exact component={StreamShow} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }
}

export default App;

And the problem is solved.