Component does not render when url loads in react-router v4 - reactjs

I want to render a modal component in a particular route, and display certain information in the modal by passing props, I also want to display the page from where the modal is opened as a background and the modal on top.
I am able to change the route but the component does not render.
How do I go about this? I had also split my routes based on different layouts in my app.js file.
App.js
render() {
let layoutAssignments = {
'/': WithLayout,
'/admin/profiles': WithLayout,
'/admin/profiles/new': WithLayout,
'/profiles':WithLayout,
'/admin/mgmt':WithLayout,
'/login': WithoutLayout,
'/donate':WithoutLayout,
'/admin/profiles/:id':WithoutLayout
}
let layoutPicker = function(props){
var Layout = layoutAssignments[props.location.pathname];
return Layout ? <Layout/> : <pre>Error 404, Page Not Found</pre>;
};
return (
<Router>
<Route path = "*" render={layoutPicker} />
</Router>
);
}
}
WithLayout.js
class WithLayout extends Component{
render(){
return(
<>
<LayoutContainer>
<Switch>
{withLayoutRoutes.map(route =><Route key={route.path} path = {route.path} component={route.component}/>)}
</Switch>
</LayoutContainer>
</>
);
}
}
withRoutes
export const withLayoutRoutes = [
{
path: path.profilesListing,
component: ProfilesContainer,
},
{
path: path.profileCreation,
component: RegistrationContainer,
},
{
path: path.adminProfilesListing,
component:ProfilesContainer,
},
{
path:path.mgmt,
component: AdminMgmt,
}
]
Place where i define the routes for the modal i want to open up
<Route path={routes.modal + `/:id`} render={(props) =>
<PlayerDetailsModal {...props} matchTableData=
{this.props.modalInfo.matches}
modalActions = {this.props.modalActions}
cardActions = {this.props.cardActions}
modalInfo = {this.props.modalInfo}
getModificationData={this.props.getModificationData}
getPlayerDeleteId={this.props.getPlayerDeleteId}
hoverIdHandler = {this.props.hoverIdHandler}
hoverId = {this.props.hoverId}
/>
I tried to implement withRouter to check for update blocking, but the problem exists.

Solved the issue, the issue was because of an extra declaration in the app.js file. Take note to use from "react-router" than from "react-router-dom". I had used used Two Routers one in index.js above app.js and one in app.js, which was the main cause of the issue.
How to push to History in React Router v4?

Related

How to solve conflict between react-router-dom v6 and mobx?

I've created dynamic routing on my site, which changes when a user login successfully. The fact of logging I keep in global state, which observers by mobx. When the user login successfully, routes changes too, and it works correctly, but in the console, there is the next problem:
Error
Error in text variant:
react-dom.development.js:67 Warning: React has detected a change in the order of Hooks called by AppRouter. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
Previous render Next render
useState useState
useState useState
useRef useRef
useDebugValue useDebugValue
useEffect useEffect
useContext useContext
undefined useContext
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There is a screenshot of the route's component:
Routes component
Routes component code:
import { observer } from "mobx-react-lite";
import { useContext } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { Context } from "../..";
import { adminPaths, guestPaths, userPaths } from "./paths";
const AppRouter = () => {
const { userStore } = useContext(Context);
return (
<Routes>
<Route path='/*' element={<Navigate to='/' />} />
{
userStore.isAuth && userPaths.map(({ path, component }) =>
<Route path={path} element={component()} />)
}
{
userStore.isAuth && adminPaths.map(({ path, component }) =>
<Route path={path} element={component()} />)
}
{
guestPaths.map(({ path, component }) => <Route path={path} element={component()} />)
}
</Routes>
)
}
export default observer(AppRouter);
When I remove the observer in this component, error disappeared, but routes don't update after login.
Routes configuration code:
Routes configuration
Routes configuration code:
import AdminCabinet from "../../pages/admin-cabinet/admin-cabinet";
import HomePage from "../../pages/home-page/home-page";
import UserCabinet from "../../pages/user-cabinet/user-cabinet";
export const guestPaths = [
{
name: 'Home',
path: '/',
component: HomePage
}
];
export const userPaths = [
{
name: 'Personal cabinet',
path: '/personalCabinet',
component: UserCabinet
}
];
export const adminPaths = [
{
name: 'Admin cabinet',
path: '/adminCabinet',
component: AdminCabinet
}
];
I would be grateful if someone helps me with this problem.
Issue
The only overt issue I see with your code is that you are directly invoking your React components instead of rendering them as JSX for React to handle and manage the component lifecycle of.
Example:
import UserCabinet from "../../pages/user-cabinet/user-cabinet";
const userPaths = [
{
name: "Personal cabinet",
path: "/personalCabinet",
component: UserCabinet,
},
];
...
const AppRouter = () => {
const { userStore } = useContext(Context);
return (
<Routes>
...
{userStore.isAuth && userPaths.map(({ path, component }) => (
<Route path={path} element={component()} /> // <-- invoking component
))}
...
</Routes>
);
};
Solution
The element prop should receive JSX. When destructuring component rename it to Component so it has a valid React component name and render as JSX. Don't forget to use a valid React key for the mapped routes.
Example:
import UserCabinet from "../../pages/user-cabinet/user-cabinet";
const userPaths = [
{
name: "Personal cabinet",
path: "/personalCabinet",
component: UserCabinet,
},
];
...
const AppRouter = () => {
const { userStore } = useContext(Context);
return (
<Routes>
...
{userStore.isAuth && userPaths.map(({ path, component: Component }) => (
<Route
key={path}
path={path}
element={<Component />} // <-- pass as JSX
/>
))}
...
</Routes>
);
};

Detect Route Change with react-router

I have to implement some business logic depending on browsing history.
What I want to do is something like this:
reactRouter.onUrlChange(url => {
this.history.push(url);
});
Is there any way to receive a callback from react-router when the URL gets updated?
You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.
history.listen() returns an unlisten function. You'd use this to unregister from listening.
You can configure your routes like
index.js
ReactDOM.render(
<BrowserRouter>
<AppContainer>
<Route exact path="/" Component={...} />
<Route exact path="/Home" Component={...} />
</AppContainer>
</BrowserRouter>,
document.getElementById('root')
);
and then in AppContainer.js
class App extends Component {
componentWillMount() {
this.unlisten = this.props.history.listen((location, action) => {
console.log("on route change");
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<div>{this.props.children}</div>
);
}
}
export default withRouter(App);
From the history docs:
You can listen for changes to the current location using
history.listen:
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
The location object implements a subset of the window.location
interface, including:
**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment
Locations may also have the following properties:
location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and
createMemoryHistory)
location.key - A unique string representing this location (supported
in createBrowserHistory and createMemoryHistory)
The action is one of PUSH, REPLACE, or POP depending on how the user
got to the current URL.
When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()
You can configure and use your routes like
import {browserHistory} from 'react-router';
class App extends React.Component {
componentDidMount() {
this.unlisten = browserHistory.listen( location => {
console.log('route changes');
});
}
componentWillUnmount() {
this.unlisten();
}
render() {
return (
<Route path="/" onChange={yourHandler} component={AppContainer}>
<IndexRoute component={StaticContainer} />
<Route path="/a" component={ContainerA} />
<Route path="/b" component={ContainerB} />
</Route>
)
}
}
Update for React Router 5.1+.
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
function SomeComponent() {
const location = useLocation();
useEffect(() => {
console.log('Location changed');
}, [location]);
...
}
react-router v6
In react-router v6, this can be done by combining the useLocation and useEffect hooks
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
const location = useLocation()
React.useEffect(() => {
// runs on location, i.e. route, change
console.log('handle route change here', location)
}, [location])
...
}
For convenient reuse, you can do this in a custom useLocationChange hook
// runs action(location) on location, i.e. route, change
const useLocationChange = (action) => {
const location = useLocation()
React.useEffect(() => { action(location) }, [location])
}
const MyComponent1 = () => {
useLocationChange((location) => {
console.log('handle route change here', location)
})
...
}
const MyComponent2 = () => {
useLocationChange((location) => {
console.log('and also here', location)
})
...
}
If you also need to see the previous route on change, you can combine with a usePrevious hook
const usePrevious = (value) => {
const ref = React.useRef()
React.useEffect(() => { ref.current = value })
return ref.current
}
const useLocationChange = (action) => {
const location = useLocation()
const prevLocation = usePrevious(location)
React.useEffect(() => {
action(location, prevLocation)
}, [location])
}
const MyComponent1 = () => {
useLocationChange((location, prevLocation) => {
console.log('changed from', prevLocation, 'to', location)
})
...
}
It's important to note that all the above fire on the first client route being mounted, as well as subsequent changes. If that's a problem, use the latter example and check that a prevLocation exists before doing anything.
If you want to listen to the history object globally, you'll have to create it yourself and pass it to the Router. Then you can listen to it with its listen() method:
// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';
// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
console.log(action, location.pathname, location.state);
});
// Pass history to Router.
<Router history={history}>
...
</Router>
Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';
This is an old question and I don't quite understand the business need of listening for route changes to push a route change; seems roundabout.
BUT if you ended up here because all you wanted was to update the 'page_path' on a react-router route change for google analytics / global site tag / something similar, here's a hook you can now use. I wrote it based on the accepted answer:
useTracking.js
import { useEffect } from 'react'
import { useHistory } from 'react-router-dom'
export const useTracking = (trackingId) => {
const { listen } = useHistory()
useEffect(() => {
const unlisten = listen((location) => {
// if you pasted the google snippet on your index.html
// you've declared this function in the global
if (!window.gtag) return
window.gtag('config', trackingId, { page_path: location.pathname })
})
// remember, hooks that add listeners
// should have cleanup to remove them
return unlisten
}, [trackingId, listen])
}
You should use this hook once in your app, somewhere near the top but still inside a router. I have it on an App.js that looks like this:
App.js
import * as React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Home from './Home/Home'
import About from './About/About'
// this is the file above
import { useTracking } from './useTracking'
export const App = () => {
useTracking('UA-USE-YOURS-HERE')
return (
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
)
}
// I find it handy to have a named export of the App
// and then the default export which wraps it with
// all the providers I need.
// Mostly for testing purposes, but in this case,
// it allows us to use the hook above,
// since you may only use it when inside a Router
export default () => (
<BrowserRouter>
<App />
</BrowserRouter>
)
I came across this question as I was attempting to focus the ChromeVox screen reader to the top of the "screen" after navigating to a new screen in a React single page app. Basically trying to emulate what would happen if this page was loaded by following a link to a new server-rendered web page.
This solution doesn't require any listeners, it uses withRouter() and the componentDidUpdate() lifecycle method to trigger a click to focus ChromeVox on the desired element when navigating to a new url path.
Implementation
I created a "Screen" component which is wrapped around the react-router switch tag which contains all the apps screens.
<Screen>
<Switch>
... add <Route> for each screen here...
</Switch>
</Screen>
Screen.tsx Component
Note: This component uses React + TypeScript
import React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'
class Screen extends React.Component<RouteComponentProps> {
public screen = React.createRef<HTMLDivElement>()
public componentDidUpdate = (prevProps: RouteComponentProps) => {
if (this.props.location.pathname !== prevProps.location.pathname) {
// Hack: setTimeout delays click until end of current
// event loop to ensure new screen has mounted.
window.setTimeout(() => {
this.screen.current!.click()
}, 0)
}
}
public render() {
return <div ref={this.screen}>{this.props.children}</div>
}
}
export default withRouter(Screen)
I had tried using focus() instead of click(), but click causes ChromeVox to stop reading whatever it is currently reading and start again where I tell it to start.
Advanced note: In this solution, the navigation <nav> which inside the Screen component and rendered after the <main> content is visually positioned above the main using css order: -1;. So in pseudo code:
<Screen style={{ display: 'flex' }}>
<main>
<nav style={{ order: -1 }}>
<Screen>
If you have any thoughts, comments, or tips about this solution, please add a comment.
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Sidebar from './Sidebar';
import Chat from './Chat';
<Router>
<Sidebar />
<Switch>
<Route path="/rooms/:roomId" component={Chat}>
</Route>
</Switch>
</Router>
import { useHistory } from 'react-router-dom';
function SidebarChat(props) {
**const history = useHistory();**
var openChat = function (id) {
**//To navigate**
history.push("/rooms/" + id);
}
}
**//To Detect the navigation change or param change**
import { useParams } from 'react-router-dom';
function Chat(props) {
var { roomId } = useParams();
var roomId = props.match.params.roomId;
useEffect(() => {
//Detect the paramter change
}, [roomId])
useEffect(() => {
//Detect the location/url change
}, [location])
}
Use the useLocation() Hook to detect the URL change and put it in dependency array in useEffect() this trick worked for me
const App = () => {
const location = useLocation();
useEffect(() => {
window.scroll(0,0);
}, [location]);
return (
<React.Fragment>
<Routes>
<Route path={"/"} element={<Template/>} >
<Route index={true} element={<Home/>} />
<Route path={"cart"} element={<Cart/>} />
<Route path={"signin"} element={<Signin/>} />
<Route path={"signup"} element={<Signup/>} />
<Route path={"product/:slug"} element={<Product/>} />
<Route path={"category/:category"} element={<ProductList/>} />
</Route>
</Routes>
</React.Fragment>
);
}
export default App;
You can use the useLocation with componentDidUpdate for getting the route change for class component and useEffect for functional component
In Class component
import { useLocation } from "react-router";
class MainApp extends React.Component {
constructor(props) {
super(props);
}
async componentDidUpdate(prevProps) {
if(this.props.location.pathname !== prevProps.location.pathname)
{
//route has been changed. do something here
}
}
}
function App() {
const location = useLocation()
return <MainApp location={location} />
}
In functional component
function App() {
const location = useLocation()
useEffect(() => {
//route change detected. do something here
}, [location]) //add location in dependency. It detects the location change
return <Routes>
<Route path={"/"} element={<Home/>} >
<Route path={"login"} element={<Login/>} />
</Routes>
}
React Router V5
If you want the pathName as a string ('/' or 'users'), you can use the following:
// React Hooks: React Router DOM
let history = useHistory();
const location = useLocation();
const pathName = location.pathname;

What are concerns with importing { history } object directly into modules and using it there?

I did stumble over a problem where I couldn't get access to a synced history object. I think it is good practice to use withRouter then. However, when using the history object provided by withRouter and pushing on it the pushed state would not be reflected in the location object provided by withRouter. Strangely enough it would be reflected in the history object originally provided to my Router.
I came up with a bit of strange solution (I think). I just import the history object into the component module where I want to use it and use it there as a local variable. It does feel hacky to import the history into my modul, and thus bypassing react tree, redux store and react router altogether.
However, it is working and not causing any bugs so far. Is there a problem that I am unaware of?
See code below.
I instantiate my history object in: store.js module:
import createHistory from 'history/createBrowserHistory';
...
const history = createHistory();
...
export { history , store }
that as you can see exports history. I then feed said history to my Router (ConnectedRouter in my case, as I am using react-router-redux) in: routes.js module
import { store , history } from '/imports/client/store';
const MyStoreRouter = () => {
return (
<Provider store={store}>
<ConnectedRouter history={ history }>
<div>
<Switch>
<Route exact path="/" component={Landing}/>
<Route path="/" component={MainApp}/>
</Switch>
</div>
</ConnectedRouter>
</Provider>
);
};
Now for the wacky part. I import the history into a display component:
DisplayComponent.js module:
import { history } from '/imports/client/store';
....
export default class EventCreationModal extends Component {
constructor() {
super();
this.handleSelect = this.handleSelect.bind(this);
this.state = {
selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
};
history.listen((location,action) => {
this.setState({
selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
})
});
}
handleSelect(key) {
history.push("/Home",{'category':key})
}
render () {
return (
<Tabs activeKey={this.state.selectedCategory} onSelect={this.handleSelect} id="SportOrSocialSelector">
<Tab eventKey={'sports} .../>
<Tab eventKey={'social} .../>
</Tabs>
)
}

React Router 4 dynamic components loaded on the fly from database

I'm migrating to React Router 4.11 from 2.5.1. In the older version, my ISOMORPHIC/UNIVERSAL app retrieves the routes/components dynamically from a database at startup and I want to retain that same functionality with 4.11.
In the 2.5.1 version of react-router, I was able to load routes & components dynamically from the database by calling _createRouter with the routes parameter being the data retrieved from my db as such:
////////////////////////
// from client entry.js
////////////////////////
async function main() {
const result = await _createRouter(routes)
ReactDOM.render(
<Provider store={store} key="provider">
<Router history={history}>
{result}
</Router>
</Provider>
dest
);
}
//////////////////////
// from shared modules
//////////////////////
function _createRouter(routes) {
const childRoutes = [ // static routes, ie Home, ForgotPassword, etc];
////////////////////////
// crucial part here
////////////////////////
routes.map(route => {
const currComponent = require('../../client/components/' + route.route + '.js');
const obj = {
path: route.route,
component: currComponent
};
childRoutes.push(obj)
});
childRoutes.push({path: '*', component: NotFoundComponent});
return { path: '', component: .APP, childRoutes: childRoutes };
}
I am frustrated that I cannot find any docs on performing the same event in 4.11. Every example shows the routes hard coded like so:
render() {
return (
<Route path='/' component={Home} />
<Route path='/home' component={About} />
<Route path='/topics' component={Topics} />
)
}
This does not appear real-world to me especially for large apps.
Can anyone point me in the direction of accomplishing the same success I had in 2.5.1 with 4.11 insofar as being able to dynamically load my routes/components on the fly from a database?
Thanks much !
Maybe this code is the solution to this issue. "dynamic route import component"
import React, {
Component
} from "react";
const Containers = () => ( < div className = "containers" > Containers < /div>);
class ComponentFactory extends Component{constructor(props){super(props);this.state={RouteComponent:Containers}}
componentWillMount() {
const name = this.props.page;
import ('../pages/' + name + '/index').then(RouteComponent => {
return this.setState({
RouteComponent: RouteComponent.default
})
}).catch(err => console.log('Failed to load Component', err))
}
render() {
const {RouteComponent } = this.state;
return (<RouteComponent { ...this.props }/> );
}
}
export default ComponentFactory
<Route path="/:page"
render={rest => <ComponentFactory
page={rest.match.params.page}
{...rest}/>}/>
In the new version, each route is just a regular react component. Therefore, you should be able to dynamically create routes as you'd create any other component.
render() {
const { routes } = this.props;
return (
<div>
{
routes.map(route => <Route path={route.path} component={route.component} />)
}
</div>
);
}
You will also need to dynamically import your components before trying to render the routes.

React router change url without page reload

When I was using react-router 0.13.3, it was ok: i was changing url and transition without reload was happening.
Now, in react-router 2.0 if I'm changing url manually, my app gets reloaded entirely instead of simple redirect.
How do i fix it?
I want to use this:
link
instead this:
<Link to="/routename">link</Link>
In few special cases.
Routes
import {Router, Route, IndexRoute} from "react-router";
import App from './components/App';
import FrontPage from './components/frontPage/FrontPage';
import User from './components/user/User';
module.exports = (
<Router>
<Route path="/" component={App}>
<IndexRoute component={FrontPage}/>
<Route path="/user/:userid" component={User}/>
</Route>
</Router>
);
There is no solution. We can either onClick script or Link.
https://github.com/reactjs/react-router/issues/3411
React Router v4 - Redirect Component
The react-router v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown.
First, import the Redirect from react-router
import { Redirect } from 'react-router';
Define the Click handler
handleOnClick = () => {
// some action...
// then redirect
this.setState({redirect: true});
}
Change Render method like,
render() {
if (this.state.redirect) {
return <Redirect push to="/yourpath" />;
}
return ( <button onClick={this.handleOnClick} type="button">Button</button> );
}
Example code :
import { Redirect } from 'react-router';
export default class ConfirmationDialog extends Component{
constructor(props)
{
super(props);
this.state = {
redirect : false
}
}
handleOnClick = () => {
// some action...
// then redirect
this.setState({redirect: true});
}
render() {
if (this.state.redirect) {
return <Redirect push to="/yourpath" />;
}
return (
//your code
<button onClick={this.handleOnClick}
type="button">Button</button>
);
}
}
Reference : https://reacttraining.com/react-router/web/api/Redirect
Usually it's due to some error, run the web on chrome with DevTools (Shift+CTRL+I). In Console enable Preserve log (keeping logs) and see what is going you may see some error, solve it and it should work without refresh.
React Router v6
The navigate method has replace option.
const navigate = useNavigate();
navigate(PATHNAME, { replace: true });
Required import:
import { useNavigate } from "react-router-dom";

Resources