DEV Community

Garrick Crouch
Garrick Crouch

Posted on

Create a Custom React.js Hook to Get Subdomains

Often times it's extremely useful to be able to easily parse the hostname or domain parts of your website. The use cases are many but we'll just look at how to make a react hook to help us get subdomain info for use in our application.

We'll use the Web API window.location.hostname. It'll return the string representation of the current host.
https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname

import * as React from 'react';

export default function useSubdomain(position = 0) {

  const [subdomain] = React.useState(() => {
    try {
      return window?.
        location?.
        hostname?.
        split('.')[position];
    } catch (err) {
      console.error(err.message);
    }
  });

  return subdomain;
}
Enter fullscreen mode Exit fullscreen mode

You can see we just create an array from the hostname parts based on the . as a delimiter, and access the array index you pass in as the argument for the call to the hook.

We could take it a step further and create a function to run this logic at any time, but for now let's just assume that we only want this to run once as we call it, so we would use it like this:

export default function MyComponent() {

  const subdomain = useSubdomain(0);

  return (
    <h1>
      The website subdomain is {subdomain}
    </h1>
  );
}
Enter fullscreen mode Exit fullscreen mode

You could add checks in to make sure you're actually on a subdomain as well, and also guards for www.

Discussion (0)