Basename not working properly - react-router

I'm attempting to use a basename with react-router as documented on the react-router docs. This is due to base href being deprecated.
Here is what I have now:
import { Route, Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import { render } from 'react-dom';
var history = useRouterHistory(createHistory)({
basename: '/subdirectory'
});
render(
<Router history={history}>
<Route path='/' component={App}>
<Route path='next' component={Next} />
</Route>
</Router>,
document.getElementById('root')
);
When I go to http://the-url.com/subdirectory the page loads as expected (rendering the App component). However, when going to http://the-url.com/subdirectory/next, I get a 404 error. My nginx config is:
location /subdirectory {
alias /path/to/index.html;
index index.html;
try_files $uri $uri/ /path/to/index.html;
}

Here is how I managed to get it to work
Set Router basename to your subdirectory like this
<Router basename="/subdirectory">
If you used create-react-app and are building using npm run build you need to set homepage in package.json for the paths to be correct in the production build
homepage: "{http://www.the-url.com/subdirectory}"
For the nginx config, let's assume your index.html is under /path/to/subdirectory/index.html. Then the following should work
location /subdirectory {
root /path/to;
try_files $uri $uri/ /subdirectory/index.html;
}

I solved it by using:
import { Router, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
const history = useRouterHistory(createBrowserHistory)({
basename: '/',
})
<Router history={history}>
I think the issue was different versions of the history package. react-router#2.2.4 uses history#2.1.2, while history is already at 4.5.1.
So make sure you install the correct version of the history package.

Using BrowserRouter
helpers/history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory();
index.js
import {BrowserRouter as Router} from "react-router-dom";
import history from "helpers/history";
.....
<Router history={history} basename={'/app'}>
...
</Router>
Using Router
helpers/history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory({ basename: '/app' });
index.js
import {Router} from "react-router-dom";
import history from "helpers/history";
....
<Router history={history}>
...
</Router>

This is too sad that react documentation does not specify anything regarding basename in react router v6. however, I tried something and it worked. please find below solution. cheers!
<HashRouter>
<Routes>
<Route path='/app'> {/* put url base here and nest children routes */}
<Route path='path1' element={ <Somecomponent1 /> } />
<Route path='path2' element={ <Somecomponent2 /> } />
</Route>
<Route path="/*" element={<Navigate to="/app/path1" />} /> {/* navigate to default route if no url matched */}
</Routes>
</HashRouter>

<HashRouter>
<Routes>
<Route path='/app'> {/* put url base here and nest children routes */}
<Route path='path1' element={ <Somecomponent1 /> } />
<Route path='path2' element={ <Somecomponent2 /> } />
</Route>
<Route path="/*" element={<Navigate to="/app/path1" />} /> {/* navigate to default route if no url matched */}
</Routes>
</HashRouter>
I was struggling this issue from 2 days approx. This article was very helpful for me.

Related

React Router + GH Pages, refresh breaking app

This isn't happening on my local server,
but when I push my create-react-app to gh-pages and try to reload anything besides the home page, or navigate directly to a routed page, the page breaks and the URL repeatedly grows looking like this...
https://hellocentral.live/about/?p=/&q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/~and~q=p=/....
Here is my file with my routes...
import React from "react";
import "./SiteContainer.scss";
import HeaderContainer from "../HeaderContainer/HeaderContainer";
import { Route, Switch } from "react-router-dom";
import About from "../About/About";
import Home from "../Home/Home";
import Music from "../Music/Music";
import Footer from "../Footer/Footer";
import Merch from "../Merch/Merch";
import Pics from "../Pics/Pics";
import Contact from "../Contact/Contact";
export const SiteContainer = () => {
return (
<div className="site-container">
<HeaderContainer />
<Switch>
<Route path="/about" component={About} />
<Route path="/merch" component={Merch} />
<Route path="/music" component={Music} />
<Route path="/pics" component={Pics} />
<Route path="/contact" component={Contact} />
<Route path="/" component={Home} />
</Switch>
<Footer />
</div>
);
};
export default SiteContainer;
here is my repo
https://github.com/monstaro/hc3/tree/master/src
The site is https://www.hellocentral.live
Any help would be appreciated!
You need to wrap the Switch component in a Router component. To do this, you need to import it from the react-router-dom package:
import { HashRouter as Router } from 'react-router-dom'
...
<Router basename={process.env.PUBLIC_URL}>
<Switch>
...
</Switch>
</Router>
I gave HashRouter as example because GH Pages does not support the other router, BrowserRouter. Probably, MemoryRouter or StaticRouter do work, but I am not sure.
Since your domain is https://www.hellocentral.live, you need to set segmentCount to 0 here.
Guess you're using an older version of rafgraph/spa-github-pages cited in a blog or something. I would recommend updating index.html with the latest version of the script and 404.html with this script.
From the docs,
Note that if you are setting up a Project Pages site and not using a custom domain (i.e. your site's address is username.github.io/repo-name), then you need to set pathSegmentsToKeep to 1 in the 404.html file in order to keep /repo-name in the path after the redirect.

React Router props `location` / `match` not updating with `ConnectedRouter`

I've got my app setup as in the docs:
Step 1
...
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'
...
const history = createBrowserHistory()
const store = createStore(
connectRouter(history)(rootReducer), // new root reducer with router state
initialState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
)
Step 2
...
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4
import { ConnectedRouter } from 'connected-react-router'
...
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
<div> { /* your usual react-router v4 routing */ }
<Switch>
<Route exact path="/" render={() => (<div>Match</div>)} />
<Route render={() => (<div>Miss</div>)} />
</Switch>
</div>
</ConnectedRouter>
</Provider>,
document.getElementById('react-root')
)
I click on a Link or even dispatch(push('/new-url/withparam'))
However the props for match location are remaining the previous values or whatever the first page was.
What is happening?
This one has bitten me many times.
Your Switch and Route etc. MUST NOT BE INSIDE A CONNECTED COMPONENT!
If the component is connected, the props for match, location, etc. don't seem to get updated and propagate down to your routes.
This means don't connect your top level App or Root, or any other nested containers between the ConnectedRouter and Route
--
Update:
You may just need to wrap your component with
<Route render={ (routerProps) => <YourConnectedComponent { ...routerProps } />
I decided to add example to here as I feel it is valuable input - even tho, it's already answered.
I had similar problem, when I pushed url into router history, it changed URL but it didn't navigate properly on the component I wanted. I googled and searched for answer for hours, until I found this thread which finally helped me to find out what I made wrong. So all credits to #ilovett.
So here is an example, if someone will need it for better understanding:
I had code similar to this:
export const routes =
<Layout>
<Switch>
<Route exact path='/' component={ Component1 } />
<Route path='/parameter1/:parameterValue' component={ Component2 } />
</Switch>
</Layout>;
<Provider store={ store }>
<ConnectedRouter history={ history } children={ routes } />
</Provider>
It was working fine when I came to a project, but then I decided to refactor Layout component and I connected it to the store which caused that Component2 stopped receiving correct values in the ownProps.match.params.parameter1 and because of that it rendered component completely wrong.
So only thing what you need to do is move Layout outside of ConnectedRouter. Nothing between ConnectedRouter and Route can be connected to the store.
Working example is this then:
export const routes =
<Switch>
<Route exact path='/' component={ Component1 } />
<Route path='/parameter1/:parameterValue' component={ Component2 } />
</Switch>;
<Provider store={ store }>
<Layout>
<ConnectedRouter history={ history } children={ routes } />
</Layout>
</Provider>

React Router - Take over at root URL

So I've got React Router set up and I'm trying to run it from WordPress.
The app routes correctly as long as you start from the root "/". However if you manually navigate to any subpage via the address bar, React Router seems to only take over from there.
For example.
Hitting / will render the homepage. If you click the link 'style-guide' it will correctly route you to /style-guide and render the page.
However, if you manually navigate to /style-guide in your address bar, react will render the homepage there, and if you now click the style-guide link it will bring you to /style-guide/style-guide
What I need to do is tell react-router to always start from the root URL.
My Routes Look Like this
import {
BrowserRouter as Router,
Route,
Redirect,
Switch,
} from 'react-router-dom'
import PageContainer from 'containers/pageContainer'
class RoutesList extends React.Component {
render() {
return (
<Router>
<div>
<Switch>
<Route path="/" component={PageContainer} />
<Route path="style-guide" component={PageContainer} />
<Route
render={() => {
return <Redirect to="/" />
}}
/>
</Switch>
</div>
</Router>
)
}
}
export default RoutesList
Make your routes exact paths
<Route exact path="/" component={PageContainer} />
<Route exact path="/style-guide" component={PageContainer} />

Routing not working in reactjs application

I have created a reactjs app having three pages (components), App, Login and Register, where I need to navigate from page to page by entering the url in the browser but the navigation is not working for me. Entering any url just shows me the 'App' page.
following is the code that I have written in main.js file of the app and the url that I am using to navigate looks something like this http://localhost:8080/#/login or http://localhost:8080/#/reg
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, NavLink, Redirect, Switch, hashHistory} from 'react-router-dom'
import App from './../jsx/App.jsx';
import Login from './../jsx/Login.jsx';
import Register from './../jsx/Register.jsx';
ReactDOM.render((
<Router history={hashHistory}>
<div>
<Route path="/" component={App}/>
<Route path="/login" component={Login}/>
<Route path="/reg" component={Register}/>
</div>
</Router>
), document.getElementById('app'))
You need to configure the route to match the root path exactly. Try this...
<Route exact path="/" component={App}/>
Remove / from your path in Route path in
<Route path="/login" component={Login}/>
<Route path="/reg" component={Register}/>
try this it's working for me
entry class
import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './Component/Layout.jsx';
import { Router, Route, IndexRoute, hashHistory } from "react-router";
import Archives from './Component/Archives.jsx';
import Settings from './Component/Settings.jsx';
import Featured from './Component/Featured.jsx';
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
//<IndexRoute component={Featured}></IndexRoute>
<Route path="archives" name="archives" component={Archives}></Route>
<Route path="settings" component={Settings}></Route>
<Route path="featured" component={Featured}></Route>
</Route>
</Router>,
document.getElementById('app'));
Layout class
{
render{
return(
<div>
{this.props.children}
<ul>
<li><Link to="archives">archives</Link></li>
<li><Link to="settings">settings</Link></li>
<li><Link to="featured">featured</Link></li>
</ul>
</div>
);
}
}
If you are using react router 4, then that looks fine. However, you can try using a as shown below:
<BrowserRouter>
<Switch>
<Route path="/" component={Home} />
</Switch>
</BrowserRouter>
This is in latest versions of react. The Home component is as below:
render() {
return (
<div>
<p>Header Section</p>
<Header/>
<p>Home component</p>
<Link to="/search">search</Link>
<Route path="/search" component={Search}/>
</div>
);
}
So most probably what you need to do is to just add a switch. Other solutions may be possible too. Hope this helps :)
Use BrowserRouter and Switch from 'react-router-dom'
if you use BrowserRouter no need to pass history as props as it handles itself.
Try this.
<Router>
<Switch>
<Route exact path="/" component={App}/>
<Route exact path="/login" component={Login}/>
<Route exact path="/reg" component={Register}/>
</Switch>
</Router>

<noscript> when using react-router v2 with browser history

I tried to use the browserHistory to make the clean URLs, but when I access the web page, the page is blank and in my console I got <'noscript'> tag. I am using react-router v2.
import React from 'react';
import ReactDOM, { render } from 'react-dom';
import App from './components/App';
import InputForm from './components/InputForm';
import FilterSummary from './components/FilterSummary';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
render((
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRoute component={InputForm} />
<Route path='/filter' component={FilterSummary} />
</Route>
</Router>
), document.getElementById('app'))
Server is WebLogic, so I am not sure how to configure it, as the example only shows it in Express JS. Any idea how to solve this?
EDIT:
Adding screenshot of the HTML response
All JSX is not rendered