Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router subdomain routing

I'm building a site using react and react-router. My site is split into two sections: front and partners section. I want the partners section to be accessed using a subdomain partner. I have written the following code since react-router does not support subdomain routing. I'm unsure whether or not this is 'good practice'. So my question is, is this a proper solution, if not, what are the alternatives?

<BrowserRouter>
  <Route path="/" render={props => {
    const [subdomain] = window.location.hostname.split('.');
    if (subdomain === 'partner') return <PartnerLayout {...props}/>;
    return <AppLayout {...props}/>;
  }}/>
</BrowserRouter>
like image 325
Rasmus Nørskov Avatar asked Jul 13 '17 20:07

Rasmus Nørskov


1 Answers

I don't use react-router, but the following should work if you just add react router jsx to the individual application components

import React from 'react';

import {MainApplication} from './Main';

function subdomainApplications (map) {
  let main = map.find((item)=> item.main);
  if (!main) {
    throw new Error('Must set main flag to true on at least one subdomain app');
  }

  return function getComponent () {
    const parts = window.location.hostname.split('.');

    let last_index = -2;
    const last = parts[parts.length - 1];
    const is_localhost = last === 'localhost';
    if (is_localhost) {
      last_index = -1;
    }

    const subdomain = parts.slice(0, last_index).join('.');

    if (!subdomain) {
      return main.application;
    }

    const app = map.find(({subdomains})=> subdomains.includes(subdomain));
    if (app) {
      return app.application;
    } else {
      return main.application;
    }
  }
}

const getApp = subdomainApplications([
  {
    subdomains: ['www'],
    application: function () {
      return 'Main!'
    }
    main: true
  },
  {
    subdomains: ['foo'],
    application: function () {
      return 'Foo!';
    }
  },
  {
    subdomains: ['bar', 'baz.bar'],
    application: function () {
      return 'Bar!';
    }
  }
]);

export default function Application () {
  const App = getApp();
  return (
    <App className="Application" />
  );
}
like image 61
Stephen Handley Avatar answered Nov 14 '22 05:11

Stephen Handley