How to place parameters at the start of url in react

Viewed 178

am trying to build a simple POS system than can be accessed by different users in different businesses what I want to achieve is that the site is hosted at one place for all the businesses but they access it through urls with unique id of the business.

So like github loads a user profile through

 https://github.com/USERNAME

I would like my system to be accesses as

 https://example.com/BUSINESS_ID

and the other urls will follow i.e

https://example.com/BUSINESS_ID/menu
https://example.com/BUSINESS_ID/pos
https://example.com/BUSINESS_ID/supplies

how can I achieve this with react.

I have tried using

`/:business_id/menu` 

and so on in my urls but the page just loads blank Any ideas and suggestions of the best way to achieve this with react will be highly appreciated

This is how I am routing

in index.js

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/:business_id/" component={App} />
        <Route path="/" component={dashboard} exact />
      </Switch>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

in app.js

  <Route path="/:business_id/"
    render={({ match: { url } }) => (
         <>
           <Route path={`${url}`} component={menu} exact />
             <Route path={`${url}orders`} component={orders} />
             <Route path={`${url}menu`} component={menu} />
         </>
     )}
  />

Everything was working fine before I introduces the parameter business_id

2 Answers

In your App.js try using the react-router match.path instead of match.url props.

From the React docs:

  • path - (string) The path pattern used to match. Useful for building nested < Route >s
  • url - (string) The matched portion of the URL. Useful for building nested < Link >s

Consider the route /:businessId. match.path would be /:businessId while match.url would have the :businessId value filled in, e.g. /3423ui67x.

<Router path={"example.com/:business_id"} exact="true"/>

will help you send the required id to example.com like example.com/3

Related