Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Hash from react router when using with Laravel

Is there a way to remove # from react router when we use it Laravel. Currently I have an Laravel app where I am using one of the blade view as SPA and it has assigned to Route::('/'). I am not able to figure out to remove hash from react-router side. History or HTML5push state settings aren't working.

Is there something I have to configure from my NGINX side ?

Help would be really appreciated.

like image 508
Meet Avatar asked Feb 26 '26 01:02

Meet


1 Answers

You need to tell Laravel's routing to route all relevant requests to your React blade view.

So, at the end of your routes.php file, you should add something like:

Route::any('{path?}', function () {
    return view('react');
})->where('path', '.+');

Or, if you want to use a controller and be able to cache your routes.:

Route::any('{path?}', 'ReactController@index')->where('path', '.+');

That takes care of the server-side stuff, I assume by your post you've already got the front-end stuff handled!


Just in case, for the 1.0.0-rc1 version of the React Router, you would have something like this near the top of your javascript code:

import createBrowserHistory from 'history/lib/createBrowserHistory';

let history = createBrowserHistory();

And you would later render your Router like so:

<Router history={history}>
    <Route path="/" component={Body}>
        <IndexRoute component={Home} />
        <Route path="about" component={About}>
        </Route>
    </Route>
</Router>

For version 0.13.x, which you seem to be using, you should add the Router.HistoryLocation parameter on your Router.run function. For example:

Router.run(routes, Router.HistoryLocation, function (Handler) {
    React.render(<Handler/>, document.body);
});

The relevant docs are on https://github.com/rackt/react-router/blob/0.13.x/doc/04%20Locations/HistoryLocation.md, unfortunately they don't seem to provide examples.

like image 104
Johnny Magrippis Avatar answered Feb 28 '26 16:02

Johnny Magrippis