0

I am trying to build multipurpose website to React using react-router v5 for routing. For normal routing we have routes like

localhost:3000/posts localhost:3000/gallery

But for some other case I want to have subdomain lets say blog.

blog.localhost:3000 // render blog component

or

subdomain.localhost:3000 // render some component.

For now this also renders the same component as localhost:3000.

So, is there any way I can do this in react?

Current routes look like this.

function App() {
  return (
    <React.Fragment>
      <React.Suspense fallback={<></>}>
        <Router history={history}>
          <Switch>
            <Redirect exact from="/" to="/home" />
            <Route exact path="/login" component={LoginPage} />
            <ProtectedRoute exact={true} path="/profile" component={ProfilePage} />
            <ProtectedRoute exact={true} path="/home" component={HomePage} />
            <ProtectedRoute exact={true} path="/gallery/:subdomain" component={Gallery} />
            <Route exact path="/gallery/post/:subdomain/:postid" component={SinglePostView} />
            <Route component={PageNotFound} />
          </Switch>
        </Router>
      </React.Suspense>
    </React.Fragment>
  );
}
Sahil Paudel
  • 548
  • 6
  • 15
  • 1
    Adding a subdomain to localhost is not possible, but see this question: https://stackoverflow.com/questions/19016553/add-subdomain-to-localhost-url – max May 26 '20 at 21:57
  • Hi @zirmax Thanks for the reply, This is part of host configuration but I wanted to know If we can do it without that config in react-router. Why the subdomain rendering the same component as without subdomain if it's not possible? – Sahil Paudel May 26 '20 at 21:59

3 Answers3

1

That's not possible, React is not a web server, React is a single page application. You must host another React application on that subdomain.

Puk
  • 319
  • 1
  • 11
0

Assuming both blog & subdomain are served through the same React application you can use the below code:

if (window.location.host.split(".")[0] !== "domain.com") {
  setSubDomain(window.location.host.split(".")[0]);
}

The setSubDomain function sets the extracted subdomain to a variable.

If however, the two subdomains are served by two different React applications, ideally you should set up the redirect at the server level.

All the best!

IronmanX46
  • 558
  • 7
  • 16
-1

The problem is that React is not a web server, what you could do is make 2 different applications in a monorepo and use shared components.

For doing that, checkout this great article: https://dev.to/ynwd/how-to-setup-react-shared-components-in-monorepo-with-tailwind-webpack-and-npm-workspace-570n

Puk
  • 319
  • 1
  • 11