To begin utilizing React Router in your React app you must first install the ‘react-router-dom’ with:
Next, you must import the react-routet-dom method using the simple vanilla JS keyword “import”
For demonstration, let’s begin by creating a simple nav bar that uses react routers’ link method. To instantiate our new routes we must first use the imported “Router” and “switch” methods from the react-router-dom. Routes are defined in the Router component that’s being imported, which then, in the switch statement we define our routes. A<Switch> looks through its children <Route>s and renders the first one that matches the current URL. Therefor, we must declare our routes from highest complexity to lowest. Otherwise, React will render all the props that the beginning of that route matches. Or you can simply define a path using “exact path”, and then set your desired path to avoid confusion about which order to create your paths. Then we render our components in each Route declaration. Notice how we are giving each route an already created About, Topics, and Home component.
Next, we wrap our nav bar links in our React Router <Link> tags and give it a path that we already defined in our switch statement earlier like so:
** Note: Behind the scenes of a <Link> tag is just rendering an HTML <a> tag with an href, so people using keyboard for navigation or screen readers are still able to use the app.
Now that we have some basic routes set up, I want to briefly touch on an issue I had when using routes in a project I was recently working on. We had a form component for creating custom business cards with the ability to then add it to your custom cards. Essentially what we wanted to do is that when the form was submitted, we want our form to make a POST request, while simultaneously re-routing to the users’ custom cards page. We couldn’t manage to get it work as we wanted it to with just using the <Link> tag around the submit button. What we needed to do is in that submit function that was passed to the form that would run onSubmit, we would make out post request, and then we would change our components router history props with our /mycards route.
Here is a quick fix if you’re trying to accomplish that same type of functionality:
Below I’ve added a link to really helpful youtube video to get you started using React Router. Good Luck! The world is yours, take your knowledge and keep spreading it.
Resources I used for this blog post: