DEV Community

Garrick Crouch
Garrick Crouch

Posted on

2

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay