1

I am serving a react app on springboot. Currently I have react-router set up. When a is clicked in the React app, it is sent to a Spring view controller that looks for the URL and return the "index" template with the react app. React router then has several routes set up. Right now basic routes are working, but I am now trying to send a parameter to the new page. I am able to send the ID to the ViewController but React-router is not able to recognize the path and returns 404. Here's the ViewController.java code.

@RequestMapping(value = {"/book/{id}"})
public String getBook(@PathVariable("id") long id) {
    System.out.println("Id is " + id);
    return "index";
}

And here's the route I'm trying to direct to, which is in a in root.js.

<Route path="/book/:id" component={Book} />

1 Answer 1

1

I had this problem, and found that using a HashRouter instead of a BrowserRouter solved it for me.

My index.js (top level JS file) looks like this.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { HashRouter } from 'react-router-dom';

ReactDOM.render(<HashRouter><App /></HashRouter>, 
document.getElementById('root'));
registerServiceWorker();

There is no need for a corresponding RequestMapping method, in fact I didn't to set up any RequestMappings for the React app. This seems to work as the HashRouter prefixes a hash symbol to all paths in the React app, which "fools" Spring into bypassing processing the URL, letting React handle it as it wants.

Disclaimer: I am a React newbie who spent days trying to solve this issue, and couldn't find an answer online. When I finally found an answer I thought it would be mean not to share it. I don't know if this is a good solution, or even the best solution, but it's simple and it works.

Sign up to request clarification or add additional context in comments.

1 Comment

This is also the direction I used to build my web app with React. React-Router warns against the usage of HashRouter but the issue is building a good resource controller that send request to the javascript side instead of the api side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.