Setting up React Router in your create-react-app
If you’re working on a react-app with multiple pages, you’ll want to check out this neat package React Router.
React Router does what the name implies — it manages the routing for your react components.
In this article, we’ll go over how to set up the basic routing for your components drawing examples from a dance site that I’m working on.
Okay, let's get started!
First, install react-router.
Once the package is installed, go to your index.js file in the root of your src directory and import BrowserRouter as Router from “react-router-dom”.
Then proceed to wrap your App component with the Router component.
By doing so, all the components within App will be able to communicate with the Router and be involved within its network.
Once you’ve done so you can start creating your Routes.
- At this point, you can draw up your routes within the App component, but in this case, I have a bunch of pages to route to and would rather keep them organized within another component called RoutesTree. I also like to keep my App component light on the number of lines of code.
But lets zoom in.
The important pieces are this.
Import Route and Switch components from “react-router-dom”
Import the components that will ultimately render a page your user will visit (any component that needs a route) into the file.
Then use the Switch component to wrap all of your Route components.
Within the Switch component tags, you can add any number of Route components. Each Route component will take a component that you imported as well as a ‘path’ prop. You can set the path property to any endpoint you choose.
You can continue this until you have a list as long as the one I showed you earlier.
But here are some notes.
- Two routes cannot have the same path
- If you have a header and footer you want to be visible on all pages, simply pull them outside of the Switch component
Like I did here in the App component.
- If you set your ‘Home’ component’s path to ‘/’, make sure to place it as the last component rendered → otherwise the Router will register the ‘/’ immediately and render the ‘Home’ component instead of your other pages (you could also add the ‘exact’ prop if you prefer)
And that's about it folks! Super easy right? I hope it helps!
I highly recommend going through the React-Router docs because they’re really well documented and the library can do some pretty neat stuff.
Now fire up your servers and start reveling in your routing power.