Routing not working when creating ui5 application using ui5-webcomponents-react

307 views Asked by At

I am creating one react app based ui5-webcomponents-react, and deploying it to the SAP BTP. Each time the app is directly loading the index.html. I am not sure how to use the react-router in this app.

Files

approuter -> xs-app.json

{
 "welcomeFile": "todoapp/"
}

public -> xs-app.json

{
  "welcomeFile": "index.html",
  "authenticationMethod": "route",
  "logout": {
     "logoutEndpoint": "/do/logout"
   },
  "routes": [
    {
      "source": "^(.*)$",
      "target": "$1",
      "service": "html5-apps-repo-rt",
      "authenticationType": "xsuaa"
    }
   ]
}

index.js

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<ThemeProvider>
    <BrowserRouter>
       <App />
    </BrowserRouter>
</ThemeProvider>
);

I have added the routes in the App.js

 /*Removed unnecessary code for clarity*/
 return(
    <Routes>
        <Route path="/" element={<Worklist/>}/>
        <Route path="/detail" element={<Detail/>}/>
    </Routes>
 )

Worklist.js

 /*Removed unnecessary code for clarity*/
 return(
    <div>Worklist</div>
 )

The initial div element (Worklist component) is not showing on the index.html page. And I have doubts about how to navigate to another page, and how the URL might look.

1

There are 1 answers

1
Etrusko On

To overcome this problem I used basename inside BrowserRouter, so the urls will be xxxx/index.html or xxxx/index.html/foobar.
I used this solution cause if you change "welcomeFile": "index.html" to "welcomeFile": "" it doesn't recognize the app.
It's probably not the prettiest solution but it's certainly the fastest and most effective for a React app inside SAP environment.
So, to use an easy router (React-Router v6), the code will be like this:

// example_complete_url = https://xxx.eu10.hana.ondemand.com/my-sap-deployed-app-url/index.html
const base_url = "/my-sap-deployed-app-url/index.html";

<BrowserRouter basename={base_url}>
    <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/foobar" element={<Foobar />} />
        <Route path="/404" element={<NotFound />} />
        <Route path="*" element={<Navigate to="/404" replace />} />
    </Routes>
</BrowserRouter>

If I find other ways to do it I'll edit my answer.


EDIT WITH SOLUTION that works with refresh or path changes:
I figure out how to manage this issue by using hashRouter from ReactRouter6. This method doesn't require using a basename like with the browserRouter. Here it is an easy example:

import { createHashRouter, RouterProvider } from "react-router-dom";

const router = createHashRouter([
  { path: "/", element: <PageHome />, },
  { path: "/page2", element: <Page2 />, },
);

const App = () => {
  return (
    <RouterProvider router={router} />
  );
};