How to Route using Subdomain in React.

How to Route using Subdomain in React.

Subscribe to my newsletter and never miss my upcoming articles

When i was making my portfolio in React , i wanted to have all components in different subdomains.

Eg :

My domain : fredy.rocks ,

I want my Projects component at projects.fredy.rocks,
My blog at blog.fredy.rocks and more.. I really wanted to do that , but i found nothing. After asking some of my seniors i finally did it with conditional component rendering .

It means if a url is having a specific subdomain , the component ( which we have assigned for the subdomain) should be rendered.

Code

We all know the Web API's . Lets use window.location API

if (window.location.host.split('.')[0] == 'projects' 
{
console.log("projects component")
}

Well this is the core idea i am using.

What is window.location

>>console.log(window.location)
>>
{hash: ""
host: "projects.fredy.rocks"
hostname: "projects.fredy.rocks"
href: "https://projects.fredy.rocks/"
origin: "https://projects.fredy.rocks"
pathname: "/"
port: ""
protocol: "https:"}

So window.location gives us the details about the current website url and other stuffs like hostname,href,pathname,protocol etc.

Our goal is to find the subdomain in the url.

>> console.log(window.location.host)
>> projects.fredy.rocks
// Here we get the host of the website and the subdomain can be extracted after spliting the above result.
>> console.log(window.location.host.split('.')[0])
>> projects
// Yes we got the subdomain after spliting the host and getting its 0th index which in here is the subdomain name.

Lets get back to React.

Lets do some basic react stuffs after using CRA template.

import Projects from "./projects/Projects";
// Projects is the component i want to render 
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
// If you are using react router inside the component better wrap the component in </Router>

function App() {
  if (window.location.host.split(".")[0] == "projects") {
// It checks if the subdomain is named projects.
    return (
      <Router>
        <Header />
        <Projects />
      </Router>
    );
  }

export default App;
// Exporting App

That's the whole code needed to setup a subdomain based router in react.

You can add a else block and render a Error page if needed.

Contact


  • Feel free to email me for Bugs Found or queries.

  • I will be happy to help.

  • Cover image taken from here
#javascript#reactjs#react-router#routing#apis
 
Share this