I am trying to redirect to an error page by passing an error message inside the Redirect component, via the "state" property.
But whenever I add the "state" property, the component(ErrorPg) associated with the redirected route does not render(and I get a blank page), even though the URL is correctly updated.
I am trying to follow the first solution here, for reference.
Relevant files below. Thank you,
ErrorHandler.tsx (file with the Redirect component)
import React from "react";
import { useLocation, Redirect } from "react-router-dom";
import { get } from "lodash";
import ErrorPg from "./c1_pages/ErrorPg/ErrorPg";
const ErrorHandler = ({ children }: any) => {
const location = useLocation();
const errorMsg = get(location.state, "errorMsg");
return errorMsg ? (
<Redirect to={{ pathname: "/error", state: { errorMsg: errorMsg } }} />
/*** If I remove the "state" property, like "<Redirect to={{ pathname: "/error" }} />", it works ***/
) : (
children
);
};
export default ErrorHandler;
Router.tsx (where I am calling the render method in the "/error" path to pass the props to the ErrorPg component).
import React, { useContext } from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";
import PrivateWrap from "./PrivateWrap";
import Login from "./c1_pages/LogReg/Login";
import Register from "./c1_pages/LogReg/Register";
import ErrorHandler from "./ErrorHandler";
import ErrorPg from "./c1_pages/ErrorPg/ErrorPg";
function Router() {
return (
<BrowserRouter>
<ErrorHandler>
<Switch>
<Route path="/register" component={Register} />
<Route path="/login" component={Login} />
<Route path="/error" render={(props) => <ErrorPg {...props} />} />
<PrivateWrap>
<PrivateRoute />
</PrivateWrap>
</Switch>
</ErrorHandler>
</BrowserRouter>
);
}
export default Router;
ErrorPg.tsx (page I want to render and make use of the props)
import React, { useState } from "react";
const ErrorPg = ({ location }: any) => {
return (
<div>
<h2>{location.state.errorMsg}</h2>
</div>
);
};
export default ErrorPg;