ReactJS/Redux - Root component page is rendered on refresh from any page - reactjs

My app has a default route that loads the component HomePage on the localhost/ path in dev mode.
But when I refresh the app from any page, the home page is displayed instead, even though the URL in my browser displays localhost/any/other/path. If I then navigate manually through the app to the /any/other/path path, the browser's URL becomes localhost/any/other/path/any/other/path.
It's like the router always thinks the current path is / on refresh.
What could the issue be? I'm using React 16 and "react-router-dom": "5.1.2".
My routes are laid out as follows:
<Provider store={store}>
<ConnectedRouter>
<div>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/proxy" component={ProxyPage} />
...
</Switch>
</div>
</ConnectedRouter>
</Provider>
And my Redux router reducer is as follows:
import { createBrowserHistory } from 'history'
const history = createBrowserHistory({
basename: window.location.pathname
})
// Reducers
combineReducers({
...
router: connectRouter(history),
...
})
In the store the router reducer starts as follows, even when loading a URL:
router: {
action: "POP",
location: {
hash: "",
pathname: "/",
query: { },
search: "",
state: undefined
}
}
Edit: Simplified my use case to be more straightforward, added more information

I am not 100% sure, but my hunch is that this behavior is more related to using Redux and ConnectedRouter than your routes, which look fine to me. 2 questions:
Are you using hot reloading?
If you take this same code and run it in a non-redux app with BrowserRouter, what happens?

When true, redirecting will push a new entry onto the history instead of replacing the current one.
Redirect push to="/somewhere/else" /
Are you using the Redirect push in your code?

Found the issue.
I had changed the default basename argument in my browserHistory's configuration, which did not work as I understood (I was trying to fix a lack of redirection issue on app launch).
Removing the basename: window.location.pathname line fixed my (self-inflicted) problem.

<Provider store={store}>
<ConnectedRouter>
<div>
<Switch>
<Route exact path="/">
<Redirect to="/home" />
</Route>
<Route exact path="/login" component={LoginPage} />
<Route exact path="/proxy" component={ProxyPage} />
...
</Switch>
</div>
</ConnectedRouter>
</Provider>

Related

Browser Router (React app ) on Github not working

i have a little React app project and i have deployed it in Github. It works, even i am using import { BrowserRouter, Link, Switch, Route } from "react-router-dom"; to routing and works ... for my home component but not for the rest. This is my code: `class App extends React.Component {
render() {
return <div>
<BrowserRouter basename={process.env.PUBLIC_URL}>
<Switch>
<Route exact path ="/" component={Show} />
<Route exact path="/contact" component={Contact}/>
</Switch>
</BrowserRouter>
</div>
}
}
export default App;`
I have used this in local machine without the "basename" and worked. Now, in the github server my problem is that it is currently showing my first component when you visit my app main url but is not working for the other component, "/contact". I am not sure if i have to use the '<Link to ' property. Anyway, i just want to know why is working for my main url path (https://namegithub.github.io/main-path/) but not for any other path (https://namegithub.github.io/main-path/contact).
Sorry is a dummy question but actually i am just giving my first steps in React.
Thanks!
you can you this code
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom'
return <div>
<Router basename={process.env.PUBLIC_URL}>
<Switch>
<Route exact path ="/" component={Show} />
<Route exact path="/contact" component={Contact}/>
</Switch>
</Router>
</div>

Navigating into the default main route in chrome extension (React)

I'm building a new chrome extension using ReactJS, and I'm trying to redirect on '/' (default) to an existing route using the component of react-router.
For some reason, I can see it when I compile it to localhost, but when I upload it as a chrome extension I can't see it anymore.
What I thought about is that maybe there is another route that is in use as the main route in chrome extension instead of '/'.
I tried to console.log it but for some reason, it is not showing me the logs.
Thanks!
<div className="App">
<BrowserRouter>
<Navbar />
<Route
path="/"
exact
render={() => <Redirect to="/navigatehere" /> }
/>
<Route
path="/navigatehere"
exact
render={() => <NavigateHere />}
/>
</BrowserRouter>
</div>
);
}
export default App;
First Of all you need Switch to use exact prop.
You can import it like this.
import {BrowserRouter, Switch, Route}
// Then you have to use
<BrowserRouter>
<div>
<Switch>
<Route path='/' exact /*render Whatever you want after this . . .*/ />
</Switch>
</div>
</BrowserRouter>
Second of all, I use component prop instead of render().
Like this -
import DummyComponent from './DummyFolder/DummyComponent;
import React from 'react'
import {BrowserRouter as Router, Switch, Route}
<BrowserRouter>
<div>
<Switch>
<Route path='/' exact component={DummyComponent}/> // This will render the component in the respective path
</Switch>
</div>
</BrowserRouter>
However render() should also work for you if you use <Switch>. It is working without Switch for rest of the router because you are not specfing path as '/' for all the <Route />. If you want to route to '/', then Switch is compulsory. You can also refer DevEd 's YouTube channel for more understanding. He has made an exclusive video on React Router. Check that out Here ◀ ◀ ◀.

You tried to redirect to the same route you're currently on in React.js

I am getting this warning even I am not on that page.
for example, when I enter to profile/index it shows me than I am in feed page.
This is my router settings
<Router>
<Switch>
<Route exact path="/profile/index" component={ProfilePage} />
<Route exact path="/feed" component={FeedPage} />
<Redirect to="/feed?time=" + Date.now() />
</Switch>
</Router>
It's same when I remove exact keyword.
I am adding Date.now() at end of redirection target to avoid js file not loading because of cache.
Thanks
Try this with the components:
import { withRouter } from 'react-router-dom
...
export default withRouter(comonentName)
You can also try using this.props.history.push instead and see if it works the way you want. You can pass props like this:
this.props.history.push({
pathname: '/pathname',
state: { key: value, key2: value2 }
})

Nested routing in React router 4

I have a component, App component, NewHome Component and Results component.
My route in component App looks like
<Route exact path="/" component={NewHome} />
<Route path="flights/search/roundtrip" component={Results} />
NewHome Routes look like
<Route path="/flights" component={FlightSearch} />
<Route path="/hotels" component={HotelSearch} />
Results component is class based react component
Only App component gets render, but component inside, I can see null in react devtools and Ui only has the part of App not part of results
<Route path="flights/search/roundtrip" component={Results}>
null
<Route />
Ideally, it should work, but I am not able to understand what I am doing wrong here. Any pointers or suggetions will be helpful. What can be the probable reasons for this kind of behaviour
This is the code where i am doing reactdom.render in index.js file
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Route path="/" component={App} />
{/* {routes} */}
</ConnectedRouter>
</Provider>,
document.getElementById("root")
)
Note: full url is something like this
http://localhost:3001/flights/search/roundtrip?search_type=roundtrip&origin=BLR&destination=MAA&travel_date=2018-01-29&return_date=2018-02-13&class_type=ECONOMY&adult_count=1&child_count=0&residentof_india=true&infant_count=0&originAndDestinationSwapped=false&activeIndexMulticity=0
NewHome gets a match prop. With that, simply contact its url with nested routes you might need.
NewHome component:
render() {
const { match } = this.props
return (
<div>
<Route path={`${match.url}/flights`} component={FlightSearch} />
<Route path={`${match.url}/hotels`} component={HotelSearch} />
</div>
)
}
I think its because you forgot a '/' in your route.
try
<Route path="/flights/search/roundtrip" component={Results} />
instead of
<Route path="flights/search/roundtrip" component={Results} />
try exporting your component after wrapping your component in withRouter HOC
import { withRouter} from 'react-router-dom';
and export the component as follows
export default withRouter(Results);
I have found out the issue, in my app i was importing Route from react-router-dom. Its available in react-router. May be a correct error message would have helped :) Thanks #sujit and #mersocarlin for giving valuable inputs.

React router history.push updates URL but doesn't update component when used with redux

I am using react and redux for my application.
I have my routes defined as follows
<HashRouter>
<div className="container">
<Route path="/register" component={Register} />
<Route path="/login" component={Login} />
</div>
</HashRouter>
And I have defined my components as
export default connect(mapStateToProps)(Login);
export default connect(mapStateToProps)(Register);
Now once the registration is done I want to redirect the user to login page. So when the login is successful I am redirecting him to login from my UserAction function as follows
UserService.register(user)
.then(
user => {
dispatch(success());
history.push('/#/login'); //<== here is the issue
},
error => {
dispatch(failure(error));
}
);
The history.push above changes the URL but doesn't load the Login component.
I also tried
export default withRouter(connect(mapStateToProps)(Login));
export default withRouter(connect(mapStateToProps)(Register));
But still no luck. Any solution how to fix this?
Note: I am not using react-router-redux
Why do you even want to change the route with history push?
It easily can be done via location.hash method ( since you use HashRouter ) and of course the browser and the react itself is enough intelligent to save it in the history of the browser.
so whenever you want to change the url just use something like :
location.hash = "/myroute/10/secondroute"
and remember that you can use <Link> component to change the url using react-router itself and not bothering yourself to manage the hash or the history.
Link provides declarative, accessible navigation around your application.
Usage:
import { Link } from 'react-router-dom'
<Link to="/about">About</Link>
OR
<Link to={{
pathname: '/courses',
search: '?sort=name',
hash: '#the-hash',
state: { fromDashboard: true }
}}/>
More informations
Have you tried :
this.context.router.push('/page');
At least can you tell me what's your redux-router version ?
In your index file I suggest you that :
import routes from './routes'
ReactDOM.render((
<Provider store={store}>
<Router history={hashHistory} routes={routes}/>
</Provider>), document.getElementById('root')
);
And in your route file :
<Route path="/" component={App}>
<IndexRoute component={requireAuth(Home)}/>
<Route path="signup" component={SignUp}/>
</Route>
Do you have errors in your console ?

Resources