How to create Private or Protected route in React Router V6
TL;DR
You can check ready code here. Try live demo here and/or watch a video walk through here.
React Router V6 is a game-changer, it has a lot of new changes in comparison to its earlier version. I wasn’t following up with the latest Router update for a while until I had to do a small project and all of sudden my previous boilerplate React project started complaining to me for setting up Routes in the wrong way. You might be thinking but how? Isn’t your previously working template be working fine? I know, I will admit, I accidentally updated the Router package to the latest version :)
At first, I had trouble figuring out dealing with nested routes, after scratching my head for a while, I finally figured it out. Pretty soon, I realized I have to deal with another change and that was to do with the Protected route. In the previous version, I had something like this.