I got this basic error display component.
It works like this: you enter the page, if you passed a prop 'redirectUrl', you set a 5 second timer and afterwards it triggers the redirect. So this redirectUrl prop is optional.
However when I made my type object it triggers the 'to' prop of Redirect to throw this error:
No overload matches this call. Overload 1 of 2, '(props: RedirectProps | Readonly): Redirect', gave the following error. Type 'string | undefined' is not assignable to type 'LocationDescriptor'. Type 'undefined' is not assignable to type 'LocationDescriptor'. Overload 2 of 2, '(props: RedirectProps, context: any): Redirect', gave the following error. Type 'string | undefined' is not assignable to type 'LocationDescriptor'.ts(2769) index.d.ts(57, 5): The expected type comes from property 'to' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<...>' index.d.ts(57, 5): The expected type comes from property 'to' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly & Readonly<...>'
How would you avoid this?
Code:
import React, { useEffect, useState } from "react";
import { makeStyles, Box, Typography } from "@material-ui/core";
import { CloseOctagonOutline } from 'mdi-material-ui';
import { Redirect } from "react-router";
const useStyles = makeStyles((theme) => ({
container: {
minHeight: "100vh",
backgroundColor: theme.palette.primary.dark,
},
icon: {
fontSize: theme.spacing(7),
color: 'red',
marginBottom: theme.spacing(1),
},
innerContainer: {
backgroundColor: "#fff",
borderRadius: 12,
maxWidth: 400,
width: '80%',
padding: theme.spacing(3),
},
title: {
marginBottom: theme.spacing(2),
},
message: {
marginBottom: theme.spacing(2),
}
}));
export interface DisplayErrorPageProps {
message: string,
title: string,
redirectUrl?: string,
}
export const DisplayErrorPage = ({ message, title, redirectUrl }: DisplayErrorPageProps) => {
const classes = useStyles();
const [redirect, setRedirect] = useState(false);
useEffect(() => {
if (redirectUrl) {
setTimeout(() => {
setRedirect(true);
}, 5000);
}
}, []);
return (
<>
{redirect && <Redirect to={redirectUrl} />}
<Box
display="flex"
justifyContent="center"
alignItems="center"
className={classes.container}
>
<Box className={classes.innerContainer}>
<Box display='flex' justifyContent='center'>
<CloseOctagonOutline className={classes.icon} />
</Box>
<Typography className={classes.title} align='center' variant='h4'>{title}</Typography>
<Typography className={classes.message} align='center' variant='body2'>{message}</Typography>
</Box>
</Box>
</>
);
};
CodePudding user response:
The Redirect
component does not accept a to
prop that can be undefined
.
So you could update your conditional rendering to check that redirectUrl
exists, like this:
{redirect && redirectUrl ? <Redirect to={redirectUrl} /> : null}