Learn React Router in 2 minutes

Had this for a while now. So our example page is getting really messy, which means it's time to break it up into multiple pages. The easiest way to do that is to using the React Router library, which is going to let us split our app component into multiple sub-components, wrap those component into routes and then have links between routes so that we can build a simple navigation between those pages and have react router basically decide between which page to render based on the configuration we give it.

We start by installing both React Router and React Router Dom, that's because React Router is built for multiple environments and we're currently using it in the web environment. Port browser router, wreck our entire app, we are going to say browser router, which renders a route or exact match which is, slash, to give it a component of homepage.

Another route, F equals slash error boundary. Next thing we have to do, create all of these pages, link from React Router Dom as well, so we now have our links here, and if we click on the error example, you can see it shows up and the URL changes and all of that.

That's basically it when it comes to React Route, you define a browser router then inside you just define routes, basically with the shape of your app, each of those routes uses a render prop to decide what to render when the URL matches that route.

Another one I wanted to show you is, if you wanted to let's say have URL params, pars them like this, you say this is ID, you can then take the matched prop and render it as match.params.id, as you can see it renders the number 15. If I change this to say, 20, its going to render-

I learned an important lesson refactoring all of that so it split into multiple examples. One, React Router and React Context don't like each other, if you nest the context inside React Router, its going to stop routing. Two, you have to be really careful with how much you pollute your low level components with stuff from context, put stuff important. It made it really difficult to reuse that button in other places when its not in the main app context.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec