React Router version 6 was released some months it is really important because React Router is one of the most used React packages.
React itself doesn't come with a router package so majority of React projects from small single page apps to big organizations use React Router.
Some weeks ago while I was trying to work on an old project I ran into an error when I updated my development packages because of my React Router update that caused breaking changes. I tried going through the documentation but sometimes you know they can be long and tedious, so I decided to write this post to help anyone who is also trying to update their project.
In the end, it’s quite simple to upgrade and not much has changed, just little code difference. Version 6 is a lot better and easier to understand than version 5, if you can upgrade, you should.
So first you can open your old project in vscode and install react-router version 6, do this by running npm install react-router-dom@6 which ensures that you install the latest version 6 and that’s what we can do here:
npm install react-router-dom@6
When you get react-router version 6 installed. Try running npm start in the terminal, you will get a failed to compile error(switch is not exported from react-router-dom).
This brings us to the first change. When we used react-router v5, we imported the switch component from the react-router package to wrap our routes, but instead in react-router v6 we use the routes component to wrap the route component.
N.B You still have to import BrowserRouter from react-router-dom to wrap your root app component. And also only Route component can be a child of Routes any other component will lead to an error.
Another important change is that your component should no longer be a child of your route component but instead the route takes in an element prop and then you pass a dynamic value to element and that dynamic value is that to be rendered component as JSX.
And lastly note that dynamic routing still works as you normal(some new features were added but it works the same).
Thanks for reading and please comment on any corrections or additions you will like to add.
Link to upgrade documentation
Top comments (0)