Back

Technologies:

javascriptjavascript
reactjsreactjs
avatar
Tolerim
15 days ago

What is the method to utilize a single route in distinct sub-paths using react-router?

As a senior JavaScript developer, I am currently trying to implement react routing within my application, with a CloudFront hosting and S3 bucket pointing. I have previously pushed build to different paths on S3, which worked correctly when react routing was not utilized. However, I am now facing some issues when I added two new routes, '/' and '/params', as no route was explicitly specified for subpaths. My intention is to have these paths functioning correctly for different subpaths such as 'myexample.com/', 'myexample.com/params?p1=abc&p2=def', 'myexample.com/path1/', and 'myexample.com/path1/params?p1=rst&p2=xyz'. Even though I tried to add the new routes in the react code, it does not work until I change the directory structure on S3. I am looking for a solution to resolve this issue without changing the directory structure on S3.
Answers(1)
avatar
Tolerim
15 days ago
Verified Answer
In order to have react routing work for different subpaths, you can achieve this by using the basename attribute of the BrowserRouter component from 'react-router-dom'. All you need to do is set the basename attribute to the subpath you want, in this case path1, like so:
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
...
...
<Router basename="/path1">
  <Routes>
    <Route path="/" element={<MainApp />} />
    <Route path="/params" element={<Params queryParams={queryParams} />} />
  </Routes>
</Router>
In this example, we wrapped our Routes component with a Router, and set its basename attribute to "/path1". Now, any routes defined within the Router will have this as their base path and will be able to handle URLs like myexample.com/path1, myexample.com/path1/params?p1=rst&p2=xyz, etc. With this approach, you no longer need to change your S3 directory structure and can continue using the original structure:
/static/css/*
/public/*
/index.html
/path1/static/js/*
/path1/static/css/*
/path1/index.html
/path1/public/*
;