Spring Boot Context path not working with React Browser Router

Viewed 242

I have React application which is packaged in Spring Boot jar. The structure inside jar after build is as follows

/static/bundle.js
/static/index.html

In Spring Boot configuration to render UI I have added

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}

Inside React App

<BrowserRouter basename="/">
  <Switch>
    <Route path="/" component={ShoppingCart} />
    <Route path="/recap" component={Recap} />
    <Route path="/confirm" component={ConfirmPayment} />
  </Switch>
</BrowserRouter>

This is working fine , I am able to access the application on root path http://localhost:8088/ . All further navigations also work like /recap.

Now I have added the context name in Spring application properties server.servlet.contextPath=/demo and code changes as below

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/demo").setViewName("forward:/index.html");
}

<BrowserRouter basename="/demo">
      <Switch>
        <Route path="/" component={ShoppingCart} />
        <Route path="/recap" component={Recap} />
        <Route path="/confirm" component={ConfirmPayment} />
      </Switch>
</BrowserRouter>

This renders the root page successfully at http://localhost:8088/demo But If I try to navigate to recap screen [history.push({pathname: "/recap" ....]it is not able to find the route. The url is changed to http://localhost:8088/demo/recap , but page not loaded.

I have searched and tried many different ways but could not succeed.

0 Answers
Related