React-Router: Switch
GitHub Repos
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.
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} /> // highlight-line
<Route path="/streams/:id/delete" exact component={StreamDelete} />
<Route path="/streams/:id/edit" exact component={StreamEdit} />
<Route path="/streams/:id" exact component={StreamShow} /> // highlight-line
</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.
Our StreamShow component is showing.
However we can just wrap our routes in a switch.
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.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.