Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 17, 2021 01:30 am GMT

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;}

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>  );}

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


Original Link: https://dev.to/localpathcomp/create-a-custom-reactjs-hook-to-get-subdomains-3mal

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To