react-complete-router to the rescue

Photo by Chris Ried on Unsplash

Have you ever found yourself in the need of making some kind of validation, change per route? You think, maybe if I change the source code, what a hassle my friend. That’s why I created react-complete-router and your guard system. Here I’m going to show you how to create a SEO guard for your react application using guards. So let’s get to business.

First of all we are going to install react-complete-router in our application, simple stuff:

npm install react-complete-router

Next, a simple App to do the routing

As you can see, simple stuff. Similar to other routers you see out there. But now we will create the magic guard that will handle SEO for us. First, we are going to create an object that is going to provide SEO data for the router.

Nothing too fancy about this, just an object that is going to match a key string later on. In the route component, we passed a seo prop, that is the actual guard that we are going to call, last thing to do is to build it:

This is pretty simple, we build a function that takes two parameters, the first one being the args passed to the guard, and the second one is a object that contains three thing:

  • router that is responsible for the route
  • route that called guard
  • router context

You can pretty much have access to the entire router from here. So we simply grab the object that we made, find the corresponding key, and build into the head of the document. Guards let you deny the route (remember that the path matching is also a guard that you can overwrite), so if you return false, the route will be canceled, since we are not checking anything, just applying effects, doing that won’t be necessary.

As you can see, you have the power to change the entire router behaviour without change it’s source code. You can make custom auths, apply the screen title. The example I gave is pretty simple, you can expand it the way you like, just don’t forget to add your custom guard in the guards prop in the router.




Um programador com sérios problemas em parar de organizar.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rafael Corrêa

Rafael Corrêa

Um programador com sérios problemas em parar de organizar.

More from Medium

🔍Creating effective (development) metrics: GQM

Be up to date even more — low latency streaming to the rescue

Decoding — StackExchange aka SEDE SQL Query for Sourcer and Recruiter

Breaking changes: creating big changes.