Home > Mobile >  Routing React Component based on hostname from the URL
Routing React Component based on hostname from the URL

Time:07-05

I want to load React Component based on host name , Example , let say We have React application 'Frontend' and URL to access this app is <base_url>/test/login or <base_url>/test/home. Now I want to access this app from 2 different host name.

  1. test.abc.com/test/login , test.abc.com/test/home
  2. test.xyz.com/test/login , test.xyz.com/test/home

Now If user use #1 then it will show the login/home/logout page for test.abc.com only and for #2 login/home/logout page is different. Basically I need to customized the UI based o hostname.

Can anyone tell me , How can I achieve this scenario or is there any other way to do that?

CodePudding user response:

  1. Test the value of location.hostname
  2. Select your component based on that
  3. Pass it to your route

For example:

import { ABCLogin, XYZLogin } from "./LoginComponents";
const Login = location.hostname === "test.abc.com" ? ABCLogin : XYZLogin;

const App = () => {
    /* ... */
    <Route path="login" element={<Login />}>
    /* ... */
}

From a comment on another answer:

If the app is running from 100 hostnames and the login/home/logut and others are different based on host name , then in this case whether this approach is applicable too?

Going from 2 (as specified in the question) to 100 is something of a goalpost move, but…

Since including 100 different Login components would bloat the application, I would do the selection at build time. The specifics would depend on which toolchain you were using to build your production app.

For example, if you were using Webpack you could do something like:

resolve: {  
    alias: {
        components: path.resolve(__dirname, 'src/components/'),
        'components/Login': path.resolve(__dirname, `src/components/${process.env.TARGETHOSTNAME}Login`)
    }
}

This would require that you set the TARGETHOSTNAME environment variable before building.

CodePudding user response:

Use window.location.hostname and useEffect to achieve desired behaviour. Basically check the url inside useEffect and redirect using ReactRouterDOM library or something similar.

CodePudding user response:

get the hostname with the javascript function location.hostname; if the hostname is test.abc.com redirect to test.abc.com/logout else redirect to test.xyz.com/logout

CodePudding user response:

Use window.location.hostname to get the hostname and split at '.'

const subdomain = window.location.hostname.split('.')[1]

if(subdomain === "abc") {
  // ... do something
} else {
  // ... do something
}

  • Related