Route Component renders multiple times when route is split into multiple files - javascript

The issue is that whenever I try to migrate my routes into another file and import them into parent file(routes.js) then whenever I tried to navigate to those migrated route the whole layout is re-rendered and if I keep migrated routes in the parent route component then the layout is rendered once as expected.
The route component where all the routes are written as below
routes.js
import React, { Component } from 'react';
import {Route, Switch} from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import MainLayout from '../pages/layouts/MainLayout';
import Login from '../components/Login/Login';
import UserList from "../components/User/UserList";
import UserCreate from '../components/User/UserCreate';
import UserEdit from '../components/User/UserEdit';
import UserSetting from '../components/User/UserSetting';
class Main extends Component {
render() {
return (
<Switch>
<Route exact path='/' component={Login}/>
<PrivateRoute exact path='/user' component={UserList} layout={MainLayout}/>
<PrivateRoute exact path='/user/create' component={UserCreate} layout={MainLayout}/>
<PrivateRoute exact path='/user/edit/:id' component={UserEdit} layout={MainLayout}/>
<PrivateRoute exact path='/user/setting/:id' component={UserSetting} layout={MainLayout}/>
</Switch>
)
}
}
export default Main;
UserRoutes.js
import UserList from "../components/User/UserList";
import UserCreate from '../components/User/UserCreate';
import UserEdit from '../components/User/UserEdit';
import UserSetting from '../components/User/UserSetting';
const UserRoutes = [
{
path : '/user',
component : UserList,
},
{
path : '/user/create',
component : UserCreate,
},
{
path : '/user/edit/:id',
component : UserEdit,
},
{
path : '/user/setting/:id',
component : UserSetting,
},
];
export default UserRoutes;
Now, when I try to import this route in place of the written routes in routes.js component, the above mentioned issue arises.
routes.js
import React, { Component } from 'react';
import {Route, Switch} from 'react-router-dom';
import PrivateRoute from './PrivateRoute';
import MainLayout from '../pages/layouts/MainLayout';
import Login from '../components/Login/Login';
import UserRoutes from './UserRoutes';
class Main extends Component {
render() {
return (
<Switch>
<Route exact path='/' component={Login}/>
{
UserRoutes.map(({ path, component }, key) =>
<PrivateRoute exact layout={MainLayout} path={path} component={component} key={key} />
)
}
</Switch>
)
}
}
export default Main;
PrivateRoute.js
import React from 'react';
import {Redirect, Route, withRouter} from 'react-router-dom';
let state_of_state = localStorage["appState"];
let Auth = {};
if (!state_of_state){
localStorage["appState"] = JSON.stringify({user : {}});
} else {
Auth = JSON.parse(state_of_state);
}
const PrivateRoute = ({ layout: Layout, component: Component, ...rest }) => (
<Route {...rest} render={props => {
const newComponent = Layout ?
<Layout><Component {...rest} {...props} /></Layout>
:
<Component {...props} />;
return (!_.isEmpty(Auth.user)) ? (
newComponent
) : (
<Redirect to={{pathname: '/', state: { from: props.location }}} />
)
}}/>
);
export default PrivateRoute;
I need some guidance where I am going wrong with this.

Related

React Router not render

I tried using react router but it doesn't work. I already know that React Router Dom v6 has changed from Switch to Routes but when I run the program it just shows a blank screen. Does anyone know how to fix this? Here is my code:
App.js
'''
import React, {Component} from "react";
import { BrowserRouter as Router } from "react-router-dom";
import { render } from "react-dom";
import HomePage from "./HomePage";
export default class App extends Component{
render() {
return (
<Router>
<div>
<HomePage />
</div>
</Router>
);
}
}
const appDiv = document.getElementById("app");
render(<App />,appDiv);
'''
HomePage.js
'''
import React,{Component} from 'react';
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { BrowserRouter as Router ,
Routes ,
Route ,
} from "react-router-dom"
export default class HomePage extends Component{
render () {
return (
<Router>
<Routes>
<Route path='/'>
<p>This is Home Page</p>
</Route>
<Route path='/join' element={<RoomJoinPage />} />
<Route path='/create' element={<CreateRoomPage />} />
</Routes>
</Router>
);
}
}
'''
The error is that "You cannot render a Router inside another Router " occurs when we have 2 Router components in the same React application.
So if u see u are calling in App.js and when u call Homepage from app.js it renders again. Thats why everything becomes blank.
and avoid using p tag inside render function in homepage.js
Try doing this:
**App.js**
import React, {Component} from "react";
import { BrowserRouter as Router } from "react-router-dom";
import { render } from "react-dom";
import HomePage from "./HomePage";
export default class App extends Component{
render() {
return (
<div>
<HomePage />
</div>
);
}
}
const appDiv = document.getElementById("app");
render(<App />,appDiv);
**Homepage.js**
import React,{Component} from 'react';
import RoomJoinPage from "./RoomJoinPage";
import CreateRoomPage from "./CreateRoomPage";
import { BrowserRouter as Router ,
Routes ,
Route ,
} from "react-router-dom"
export default class HomePage extends Component{
render () {
return (
<Router>
<Routes>
<Route path='/'>
</Route>
<Route path='/join' element={<RoomJoinPage />} />
<Route path='/create' element={<CreateRoomPage />} />
</Routes>
</Router>
);
}
}

Question about PrivateRoutes and to get navigated back to login page

Hi I need help getting my code to work so that when I try to log back in I won't be able to view the dashboard since I logged out. Right now its giving me a blank screen in my project and I think its because privateroute isn't a thing anymore? Not sure. This is my code in PrivateRoute.js:
import React, { Component } from 'react';
import { Route, Navigate } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const PrivateRoute = ({ component: Component, auth: { isAuthenticated, loading },
...rest }) => (
<Route {...rest} render={props => !isAuthenticated && !loading ? (<Navigate to='/login' />) : (<Component {...props} />)} />
)
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStatetoProps = state => ({
auth: state.auth
});
export default connect(mapStatetoProps)(PrivateRoute);
This is the code for the app.js:
import React, { Fragment, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import Alert from './components/layout/Alert';
import Dashboard from './components/dashboard/Dashboard';
import PrivateRoute from './components/routing/PrivateRoute';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import { loadUser } from './actions/auth';
import setAuthToken from './utils/setAuthToken';
import './App.css';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<Navbar />
<Routes>
<Route exact path='/' element={<Landing/>} />
</Routes>
<section className="container">
<Alert />
<Routes>
<Route exact path='/Register' element={<Register/>} />
<Route exact path='/Login' element={<Login/>} />
<PrivateRoute exact path='/dashboard' element={Dashboard} />
</Routes>
</section>
</Fragment>
</Router>
</Provider>
)};
export default App;
Please Help!
there is a recommended Protected Route implementation in the v6 react router docs you can follow.
DOCS IMPLEMENTATION
Your issue:
<Route {...rest} render={props => !isAuthenticated && !loading ?
(<Navigate to='/login' />) : (<Component {...props} />)} />
This Route is not up to date with v6, which I assume you are using, you need to update it.
Exact is also not supported anymore, there is no point in including it in your routes.
If you are not using v6 please update your post and include your react-router version.

not being able to pass url parameters in react.js

I am working on a React.js web app , for some reasons I am not able to pass url parameters.
An example is being shown below:
Routes:
import React from "react";
import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom';
import Helloworld from './components/helloworld/helloworld.component';
import SecondView from './components/secondview/secondview.component';
import ThirdView from "./components/thirdview/thirdview.component";
const AppRoutes = () => (
<BrowserRouter>
<Switch>
<Route exact path='/' component={Helloworld}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/thirdview' component={ThirdView}/>
<Route path='/thirdview/:number' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>
</BrowserRouter>
);
export default AppRoutes;
Secondview Component
import React from 'react';
import {Link, withRouter} from 'react-router-dom';
class SecondView extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log("I am being called SecondView component...");
}
render() {
return (
<div className={"boxDiv"}>
<p>Second View</p>
<Link to={{pathname: '/thirdview/7'}}> GO to third view with parameter value. </Link>
</div>
);
}
}
export default withRouter(SecondView);
Thirdview comopnent:
import React from 'react';
import { Route, Link,withRouter } from 'react-router-dom';
import FourthView from "../fourthview/fourthview.component";
class ThirdView extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
render() {
console.log(this.props.match.params);
return (
<div className={"boxDiv"}>
<p>Third View</p>
{ console.log(this.props)}
<h1>parameter passed: (#{this.props.params.number})</h1>
</div>
);
}
}
export default withRouter(ThirdView);
What I want, is to be able to get /:number value on my thirdview component! Anyone knows how to achieve such thing in React.js? Are there other ways doing this?
What I get is empty object!
I think it should be:
{this.props.match.params.number}
instead of
{this.props.params.number}
and you don't need withRouter on ThirdView and SecondView as are passed to Route already.
EDIT:
Since you want to render the same component for /thirdview and /thirdview/7 use optional param matcher
<Switch>
<Route exact path='/' component={Helloworld}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/thirdview/:number?' component={ThirdView}/>
<Redirect from='*' to='/' />
</Switch>

react pass children element from router

I have a react app setup by dva 2.0.1. In the routers.js, I have:
import React from 'react';
import { Router, Switch, Route, IndexRoute } from 'dva/router';
import IndexPage from './routes/IndexPage'
import CountPage from './routes/CountPage'
function RouterConfig({ history }) {
return (
<Router history={history}>
<Route path="/" component={IndexPage}>
<Switch>
<Route path="/count" component={CountPage}/>
<Route path="/statements" component={CountPage}/>
</Switch>
</Route>
</Router>
);
}
export default RouterConfig;
And in my IndexPage, I have:
import React from 'react';
import { connect } from 'dva';
import styles from './IndexPage.css';
import { Layout } from 'antd'
import Header from '../components/Header'
const { Sider, Content, Footer } = Layout;
const IndexPage = (props) => {
const { children, routes } = props;
console.log(props);
return (
<Layout>
<Header routes={routes}>header</Header>
<Layout>
<Sider>sider</Sider>
<Content>{children || "No content"}</Content>
</Layout>
</Layout>
);
}
IndexPage.propTypes = {
};
export default connect()(IndexPage);
However, the console.log(props); gives dispach, history, etc. But children and routes are not in it.
What happened?
You don't have any child component on your Index component.
If you change this
<Route path="/" component={IndexPage}>
to this
<Route path="/" component={()=>(<IndexPage><p>This is a child component</p></IndexPage>)}>
you can see the child components inside your Index component.
It turns that I was using react-router#2 syntax and should be react-router#4.

TypeError: Cannot read property 'history' of undefined

I'm trying to redirect the user to the login page when the /logout routes is hit. The auth is working (jwt token is removed, but the app fails to redirect to /login.
Also If I do to / the app crashes as well.
On the Login route I uses withRouter from the react-router-dom package wih this I can access the this.props.history.push('/redirect_to_a_new_path'), but when I try to wrap the App component with withRouter method it crashes as well.
Please help!
Here is the github repo:
App.js
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
withRouter
} from "react-router-dom";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import lightBaseTheme from "material-ui/styles/baseThemes/lightBaseTheme";
import getMuiTheme from "material-ui/styles/getMuiTheme";
import injectTapEventPlugin from "react-tap-event-plugin";
// Components
import Navbar from "./components/Navbar";
import HomePage from "./components/HomePage";
import SpotMap from "./components/SpotMap";
import SignUpPage from "./components/containers/SignUpPage";
import LoginPage from "./components/containers/LoginPage";
import DashboardPage from "./components/containers/DashBoardPage";
import NotFound from "./components/NoteFound";
import Auth from "./modules/Auth";
import "./styles/App.css";
injectTapEventPlugin();
const handleLogout = event => {
Auth.deauthenticateUser();
this.props.history.push("/login");
};
const isLoggedIn = event => {
if (Auth.isUserAuthenticated()) {
this.props.history.push(DashboardPage);
} else {
this.props.history.push(HomePage);
}
};
class App extends Component {
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
<Router>
<div>
<Navbar />
<Switch>
<Route exact path="/" component={isLoggedIn} />
<Route path="/spotmap" component={SpotMap} />
<Route path="/dashboard" component={DashboardPage} />
<Route path="/signup" component={SignUpPage} />
<Route path="/login" component={LoginPage} />
<Route path="/logout" component={handleLogout} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
</MuiThemeProvider>
);
}
}
export default App;
This is written in React Router v3 and this is what I need to convert to React Router V4. The routes that does not work for me are the "/" and "logout" routes.
import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
import DashboardPage from './containers/DashboardPage.jsx';
import LoginPage from './containers/LoginPage.jsx';
import SignUpPage from './containers/SignUpPage.jsx';
import Auth from './modules/Auth';
const routes = {
// base component (wrapper for the whole application).
component: Base,
childRoutes: [
{
path: '/',
getComponent: (location, callback) => {
if (Auth.isUserAuthenticated()) {
callback(null, DashboardPage);
} else {
callback(null, HomePage);
}
}
},
{
path: '/login',
component: LoginPage
},
{
path: '/signup',
component: SignUpPage
},
{
path: '/logout',
onEnter: (nextState, replace) => {
Auth.deauthenticateUser();
// change the current URL to /
replace('/');
}
}
]
};
export default routes;
For the / route you should use render like this:
<Route exact path="/" render={() => {
if (Auth.isUserAuthenticated()) {
(<DashboardPage)/>)
} else {
(<HomePage/>)
}
}} />
For your /logout route using <Redirect>
<Route path="/logout" render={() => {
Auth.deauthenticateUser();
return <Redirect to={{ pathname: "/login" }} />;
}}
/>
I post a second solution for the /logout path using withRouter and this.props.history.push('/login').
Point the /logout Route to its own component "Logout"
wrap the Logout component with withRouter method from react-router-dom.
Logout.js
import React, { Component } from "react";
import Auth from "../modules/Auth";
import { withRouter } from "react-router-dom";
class Logout extends Component {
constructor(props) {
super(props);
this.handleLogout = this.handleLogout.bind(this);
}
handleLogout() {
Auth.deauthenticateUser();
this.props.history.push("/login");
}
render() {
return (
<div>
{this.handleLogout()}
</div>
);
}
}
export default withRouter(Logout);
I would use useHistory.
Do:
import { useHistory } from 'react-router-dom';
Instead of:
import { useHistory } from 'react-router';
(Or else the same error message will appear.)

Categories

Resources