React Router - Stay at the same page after refresh - javascript

I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:
<Provider store={store}>
<Router path="/" history={browserHistory}>
<Route path="/home" component={App}>
<Route path="/" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')
In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.
There is code from App.jsx
class App extends Component {
render() {
return (
<div className="app-comp">
<Navigation />
<div> {this.props.children}</div>
</div>
)
}
}
I also attach gif which shows my problem.
https://gifyu.com/image/boMp
In backend i use Firebase if it's important.
Thanks in advance.

I found the reason of my problem. I use also Firebase in my project and it causes the problem.
Thanks guys for help.
EDIT ======================================================================
Mabye I will write how I've fixed my problem and what was the reason of it.
So i was checking if user is logged in or not in auth method. And there if user was authorized I was pushing / to browserHistory.
It was mistake because every refresh method was executing and then also redirection was called as well.
Solution is just to check if during executing auth method I'm on Signin page or not. If it is Signin page then I'm pushing / to browserHistory but if not then just don't push anything.
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
let currentPathname = browserHistory.getCurrentLocation().pathname;
if( currentPathname === "/" || currentPathname === "/signin"){
browserHistory.push('/');
}
const { email } = user;
store.dispatch(logUser(email));
}
else {
browserHistory.replace('/signin');
}
})
I know that it's not pretty solution but it works and it was only home project which was created to learn react. (btw this project is using old react router 3.0 so probalby now using browserHistory is deprecated)

Check that firebase does not interfares with the client side routes :P
You can use Index routes to achieve this.
You have your navigation i.e the layout of all pages in your app component so make it the root route.
Then you want your home route to be your default route so make it your Index route.
You need to import IndexRoute from react-router package (from which you import Route).
Add this-
import { Router, Route, IndexRoute } from 'react-router';
and then make your routes like below.
Use this-
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/home" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')

it's a Server-side vs Client-side issue
check the following thread, it might give you some insights.. React-router urls don't work when refreshing or writting manually

Below example you can refer for :
React Router Navigation
Browser Refresh Issue.
Browser Back Button Issue.
Please make sure you have installed react-router-dom
If not installed. Use this command to install npm i react-router-dom
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import Page1 from "./Page1";
import Page2 from "./Page2";
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={Page1} />
<Route path="/page2" component={Page2} />
</Switch>
</BrowserRouter>,
rootElement
);
Page1.js
import React from "react";
import {Link } from "react-router-dom";
function Page1() {
return (
<div>
<p>
This is the first page.
<br />
Click on the button below.
</p>
<Link to="/page2"><button>
Go to Page 2
</button>
</Link>
</div>
);
}
export default Page1;
Page2.js
import React from "react";
function Page2() {
return (
<div>
<p>This is the second page.</p>
</div>
);
}
export default Page2;

Add into your webpack.config.js this option
devServer: {
historyApiFallback: true
},

Route tag returns the first matching component.
I think you have interchanged the paths of home and app component.
try this.
<Provider store={store}>
<Router path="/" history={browserHistory}>
<Route path="/" component={App}>
<Route path="/home" component={Home}/>
<Route path="/allhotels" component={AllHotels}/>
<Route path="/addhotel" component={AddHotel} />
<Route path="/about" component={About} />
</Route>
<Route path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Router>
</Provider>, document.getElementById('root')

Related

Page Not Found Component displaying on all pages?

I have just about completed my first real React JS project except for one bug. My 404/Page Not Found component is displaying on all pages. I have looked all over the internet and through multiple similar questions here on SO, but I am still at a loss of how to fix this problem. Here is the relevant code (with parts irrelevant to the issue removed; I can provide more code if it is necessary):
Module imports:
import React, { Component } from 'react';
import { BrowserRouter as Switch, Route, Router } from "react-router-dom";
State/login functions/authorized pages route guards here:
render() {
return (
<div>
<Router history={history} >
<Switch>
<Route render={(props) => (<HeaderNavbar {...props} handleLogin={this.handleLogin} handleLogout={this.handleLogout} loggedInStatus={this.state.loggedInStatus} role={this.state.role} key="header"/>)}/>
<Route exact path="/" component={TitlePage} />
<Route exact path="/register" component={Register} />
<Route exact path="/login" render={(props) => (<Login {...props} handleLogin={this.handleLogin} key="login" />)}/>
{this.state.role === "Student" ? (
this.studentAuthorizedPages()) :
null}
<Route exact path="/profile" component={UserProfile} />
{this.state.role === "Instructor" ? (
this.instructorAuthorizedPages()) :
null}
{this.state.role === "Administrator" ? (
this.adminAuthorizedPages()) :
null}
<Route component={PageNotFound} />
{/* <Route path='/404' component={PageNotFound} />
<Redirect to="/404" /> */}
</Switch>
</Router>
</div>
);
}
}
I believe this issue has something to do with {Switch}'s direct parent-child requirement, but I'm not sure.
So far I have tried:
Adding additional <Switch></Switch> around other parts of the code inside <Switch>. I tried this to see if it was a parent-child issue; but the bug remained.
Removing the line with HeaderNavbar in it.
Writing the {PageNotFound} route as either of the following:
Route path="*" component={PageNotFound}
Route path="" component={PageNotFound}
Using a Redirect statement (as is commented out in the code above). This prevented the app from displaying the {PageNotFound} component on every page, but then the app routed to the {PageNotFound} component on initial load, any page refresh or when a user logs out (which makes sense because logging out Routes the user back to the title page; hence basically the same as an initial load).
These are the main approaches I have tried in addition to some other smaller changes which didn't amount to anything.
I am using:
React 16.13.1
React-Router 5.1.2
Any help would be greatly appreciated.
You messed up with Switch, BrowserRouter and Router:
Change
import { BrowserRouter as Switch, Route, Router } from "react-router-dom";
to
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
according to this pattern:
<Router> // or BrowserRouter
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/topics">
<Topics />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
see here
If you want to use history prop, change BrowserRouter to just Router. Docs:
import { Router, Route, Switch } from "react-router-dom";

Can't get react-router-dom to work (seeing blank page)

This is my App component that has 3 child components: Home, Contact and Procedures. I'm trying to make each child component into its own url route.
However right now I'm just seeing a blank page
FYI- I'm using react-router-dom#6.0.2
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import Home from './Home.js'
import Contact from './Contact.js'
import Procedures from './Procedures.js'
import './App.css';
function App() {
return (
<BrowserRouter>
<Routes>
<Route exact path="/" component={Home} />
<Route path="/procedures" component={Procedures} />
<Route path="/contact" component={Contact} />
</Routes>
</BrowserRouter>
);
}
export default App;
In react-router-dom version 6 you should use element instead of component, also be sure to reference the element you want to render as JSX. By the way, there is no longer any "exact" attribute.
Should look like this on your code:
<Route path="/" element={<Home />} />

Can't make React-Router render two different components, always render root

I have these two components that are completely independent of each other. I want to render App when I enter / and render About when I go to /#/about
I got this piece of code (but I tested quite a few others):
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router'
import App from './App';
import About from './About';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App} >
<Route path="/about" component={About} />
</Route>
</Router>
, document.getElementById('root')
);
I also tried something like
<Route path="/about" component={About} />
<Route path="/" component={App} />
And changed /about to /#/about, about
But it always render the "fallback" /, it always goes to this route, no matter what.
How can I make this app navigate properly to / and /about and render the App and the About components?
#edit
Assuming that my About component is broken, I removed the first Route and kept only the /about (kept only the /about Route) :
<Route path="/about" component={App} />
(I tried keeping About as well in a previous test) and also changed the /about to about and /#/about.
And I get this error on console:
"VM3651 bundle.js:30801 Warning: [react-router] Location "/#/about" did not match any routes"
#edit 2
I made a change, following the example #Dominic posted. I had to make some modifications to make sure both components would render. I added the {this.props.children} to all Components to understand what would happen.
//imports
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={About} >
<IndexRoute component={App} />
<Route path="/about" component={Other} />
</Route>
</Router>
,document.getElementById('root'));
The route http://localhost:3000/#/about is rendering:
> About > App
So it is rendering the IndexRoute, it is not getting caught by the /about.
And this is now exactly what I need, because I didn't want a root component, I wanted 2 routes to 2 different and isolated components. I need something like two sibling routes.
#edit
The About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
<div>
About page
{this.props.children}
</div>
);
}
}
export default About;
Solution:
Since I'm using a HASH (#) in the URL, I should use hashHistory from React Router in the <Router history={hashHistory}>
You're confusing how routes work - About is a child of the App route, so in order to render About, it has to render App.
In other words your App component is the "shell" and all components under it render INSIDE it (via props.children).
You should add another route to render /.
import { ..., IndexRoute } from 'react-router'
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="about" component={About} />
</Route>
Your App does not contain route specific content, it would be something more like this:
<div id="app">
<nav>app navigation</nav>
<main class="route-content">{props.children}</main>
</div>
Docs: https://github.com/ReactTraining/react-router/blob/master/docs/guides/RouteConfiguration.md#adding-an-index
Those routes look correct to me. Are you getting any errors in the console? Maybe your About component is undefined and thus not rendering. Can you post your About component?

how to fix the "router no longer defaults the history prop to hash history" warning?

i'm using browser history and here is my code in routes.js
export default (
<Router history={browserHistory}>
<Route path="/" component={Main}>
<Route path="home/:username" component={Home}>
<IndexRoute component={HomeContent}></IndexRoute>
<Route path="widget/:second" component={Widget}></Route>
<Route path="email/:second" component={Email}>
<Route path="compose" component={ComposeEmail}></Route>
<IndexRoute component={CheckEmail}></IndexRoute>
</Route>
<Route path="social/:second" component={Social}></Route>
<Route path="calendar/:second" component={Calendar}></Route>
</Route>
<IndexRoute component={Login}></IndexRoute>
</Route>
</Router>
);
and i used this.context.router.push('/') to make a navigation. and i have no idea why this warning is keep showing in my console?
"Warning: [react-router] `Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead."
i already read the documentation at https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history but it does not really help.
i appreciated any help :)
You need to use hashHistory instead of browserHistory. Considering you're using the import synthax you can import hashHistory from react-router to replace browserHistory.
import { hashHistory, Router, ... } from 'react-router';
const history = new hashHistory();
export default (
<Router history={history}>
...
</Router>
);

React-Router: No Not Found Route?

Consider the following:
var AppRoutes = [
<Route handler={App} someProp="defaultProp">
<Route path="/" handler={Page} />
</Route>,
<Route handler={App} someProp="defaultProp">
<Route path="/" handler={Header} >
<Route path="/withheader" handler={Page} />
</Route>
</Route>,
<Route handler={App} someProp="defaultProp">
<Route path=":area" handler={Area} />
<Route path=":area/:city" handler={Area} />
<Route path=":area/:city/:locale" handler={Area} />
<Route path=":area/:city/:locale/:type" handler={Area} />
</Route>
];
I have an App Template, a HeaderTemplate, and Parameterized set of routes with the same handler (within App template). I want to be able to serve 404 routes when something is not found. For example, /CA/SanFrancisco should be found and handled by Area, whereas /SanFranciscoz should 404.
Here's how I quickly test the routes.
['', '/', '/withheader', '/SanFranciscoz', '/ca', '/CA', '/CA/SanFrancisco', '/CA/SanFrancisco/LowerHaight', '/CA/SanFrancisco/LowerHaight/condo'].forEach(function(path){
Router.run(AppRoutes, path, function(Handler, state){
var output = React.renderToString(<Handler/>);
console.log(output, '\n');
});
});
The problem is /SanFranciscoz is always being handled by the Area page, but I want it to 404. Also, if I add a NotFoundRoute to the first route configuration, all the Area pages 404.
<Route handler={App} someProp="defaultProp">
<Route path="/" handler={Page} />
<NotFoundRoute handler={NotFound} />
</Route>,
What am I doing wrong?
Here's a gist that can be downloaded and experimented on.
https://gist.github.com/adjavaherian/aa48e78279acddc25315
DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.
I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.
For react-router 1, 2 and 3
If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)
<Route path='*' exact={true} component={My404Component} />
If you want to display a 404 page but change the url (Same functionality as DefaultRoute)
<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />
Example with multiple levels:
<Route path='/' component={Layout} />
<IndexRoute component={MyComponent} />
<Route path='/users' component={MyComponent}>
<Route path='user/:id' component={MyComponent} />
<Route path='*' component={UsersNotFound} />
</Route>
<Route path='/settings' component={MyComponent} />
<Route path='*' exact={true} component={GenericNotFound} />
</Route>
For react-router 4 and 5
Keep the path
<Switch>
<Route exact path="/users" component={MyComponent} />
<Route component={GenericNotFound} />
</Switch>
Redirect to another route (change url)
<Switch>
<Route path="/users" component={MyComponent} />
<Route path="/404" component={GenericNotFound} />
<Redirect to="/404" />
</Switch>
The order matters!
In newer versions of react-router you want to wrap the routes in a Switch which only renders the first matched component. Otherwise you would see multiple components rendered.
For example:
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
browserHistory,
Switch
} from 'react-router-dom';
import App from './app/App';
import Welcome from './app/Welcome';
import NotFound from './app/NotFound';
const Root = () => (
<Router history={browserHistory}>
<Switch>
<Route exact path="/" component={App}/>
<Route path="/welcome" component={Welcome}/>
<Route component={NotFound}/>
</Switch>
</Router>
);
ReactDOM.render(
<Root/>,
document.getElementById('root')
);
With the new version of React Router (using 2.0.1 now), you can use an asterisk as a path to route all 'other paths'.
So it would look like this:
<Route route="/" component={App}>
<Route path=":area" component={Area}>
<Route path=":city" component={City} />
<Route path=":more-stuff" component={MoreStuff} />
</Route>
<Route path="*" component={NotFoundRoute} />
</Route>
This answer is for react-router-4.
You can wrap all the routes in Switch block, which functions just like the switch-case expression, and renders the component with the first matched route. eg)
<Switch>
<Route path="/" component={home}/>
<Route path="/home" component={home}/>
<Route component={GenericNotFound}/> {/* The Default not found component */}
</Switch>
When to use exact
Without exact:
<Route path='/home'
component = {Home} />
{/* This will also work for cases like https://<domain>/home/anyvalue. */}
With exact:
<Route exact path='/home'
component = {Home} />
{/*
This will NOT work for cases like https://<domain>/home/anyvalue.
Only for https://<url>/home and https://<domain>/home/
*/}
Now if you are accepting routing parameters, and if it turns out incorrect, you can handle it in the target component itself. eg)
<Route exact path='/user/:email'
render = { (props) => <ProfilePage {...props} user={this.state.user} />} />
Now in ProfilePage.js
if(this.props.match.params.email != desiredValue)
{
<Redirect to="/notFound" component = {GenericNotFound}/>
//Or you can show some other component here itself.
}
For more details you can go through this code:
App.js
ProfilePage.js
For those who are using react router v6
Redirect component has been removed from the react-router version 6.
For react-router-dom v6, simply replace Redirect with Navigate
Migrating up to v6
npm install react-router-dom#6
import {Routes, Route, Navigate } from "react-router-dom";
function App() {
return (
<div>
<Routes>
<Route path="/404" element={<div>Choose the correct path/div>} />
<Route path="*" element={<Navigate replace to="/404" />} />
</Routes>
</div>
);
}
According to the documentation, the route was found, even though the resource wasn't.
Note: This is not intended to be used for when a resource is not found. There is a difference between the router not finding a matched path and a valid URL that results in a resource not being found. The url courses/123 is a valid url and results in a matched route, therefore it was "found" as far as routing is concerned. Then, if we fetch some data and discover that the course 123 does not exist, we do not want to transition to a new route. Just like on the server, you go ahead and serve the url but render different UI (and use a different status code). You shouldn't ever try to transition to a NotFoundRoute.
So, you could always add a line in the Router.run() before React.render() to check if the resource is valid. Just pass a prop down to the component or override the Handler component with a custom one to display the NotFound view.
The above answers are correct and for react 5 before. In React v6, Switch no longer exists. This solution is for react v6:
import {BrowserRouter as Router, Routes, Route, Link} from "react-router-dom";
...
<Router>
<ul>
<li>
<Link to="t1">component1</Link>
</li>
<li>
<Link to="t2">component2</Link>
</li>
</ul>
<Routes>
<Route path="/t1" exact element={<Component1/>}/>
<Route path="/t2" exact element={<Component2/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</Router>
I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:
if (!place) return <NotFound />;
hope that helps!
React Router v6
Live Demo: Redirect Default or 404 Routes with React Router
Example code:
<Router>
<Routes>
<Route path="users" element={<Users />} />
<Route path="posts" element={<Posts />} />
</Routes>
</Router>
To redirect and navigate to one of our chosen routes, we can use <Navigate> component from React Router. Now we can declare below our route configuration the case for empty routes, like this:
<Router>
<Routes>
<Route path="users" element={<Users />} />
<Route path="posts" element={<Posts />} />
<Route path="" element={<Navigate to="/users" />} />
</Routes>
</Router>
I had similar issue, instead of using * wild identifier or Default Switch Component. We can simply just use Route Component without defining path.
example:
<Switch>
<Route path="/" component={Root} />
<Route path="/home" component={Home} />
<Route component={NotFoundPage} />
// Default Component To load If none of the path matches.
</Switch>

Categories

Resources