Home > Net >  How to redirect user to different pages based on subdomain routing and folder based routing React.js
How to redirect user to different pages based on subdomain routing and folder based routing React.js

Time:12-06

i am working on one React.js Project, in this current project all the url look like this

Home page url:dev-pcm.io/mydomain-name
Login Page url:dev-pcm.io/mydomain-name/auth
cart Page url:dev-pcm.io/mydomain-name/checkout
Order Page url:dev-pcm.io/mydomain-name/my-orders

//Here if i have button i am redirecting to any other page like this

import {useParams,useHistory} from "react-router-dom"
const function Button()=>{
const params=useParams();
const history=useHistory();

//is there any good approach to get rid from these checks

const goto=()=>{
    
    if (params?.url) {
history.push(`/${params.url}/my-orders`);
      
    } else {
     history.push(`/my-orders`);
    }
  };
return <button>
MY Order Page
</button>}

React Router Paths

    const Routes=[{
        path: "/:url",
        component: Home,
        exact: true,
      },
 {
        path: ["/:url/my-orders","/my-orders"],
        component: MyOrders,
        exact: true,
      },
]

Now i have requirement user also wants to support Url Like this

Home page url:mydomain-name
    Login Page url:mydomain-name/auth
    cart Page url:mydomain-name/checkout
    Order Page url:mydomain-name/my-orders

How can i support these both both routing.

CodePudding user response:

can have multiple path name for routes

const Routes=[{
        path: {["/:url", "/"]},
        component: Home,
        exact: true,
      },
 {
        path: {["/:url/my-orders", "/my-orders"}],
        component: MyOrders,
        exact: true,
      },
]
 

CodePudding user response:

In React, you can use the componentWillMount lifecycle method to check the current URL and redirect the user to a different page if necessary. For example, if you want to redirect users to a page based on the subdomain, you could use the following code:

componentWillMount() {
  const { hostname } = window.location;
  if (hostname === 'subdomain.example.com') {
    this.props.history.push('/subdomain-page');
  }
}

Similarly, you can use the componentWillMount method to check the current URL and redirect the user to a page based on the URL path. For example, if you want to redirect users to a page based on the folder in the URL, you could use the following code:

componentWillMount() {
  const { pathname } = window.location;
  if (pathname.startsWith('/folder')) {
    this.props.history.push('/folder-page');
  }
}

Note that in both examples, the history object is being used to push a new URL onto the history stack, which will cause the router to navigate to the specified page.

  • Related