DEV Community

Cover image for How to Route using Subdomain in React.
Fredy Somy
Fredy Somy

Posted on

How to Route using Subdomain in React.

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

Eg :

My domain : https://fredy.rocks/ ,

I want my Projects component at https://projects.fredy.rocks/,

My blog at https://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")
}
Enter fullscreen mode Exit fullscreen mode

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:"}

Enter fullscreen mode Exit fullscreen mode

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.

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
christophergwgreen profile image
Chris Green

I went through the sign up process to express how annoying this article is in terms of it being 100% useless and frustrating