Basically, I am trying to route a user based on whether or not the page exists. So I tried to do an if statement to check the prop profileExists
. If it is true, it would stay on the same page. Otherwise, it would reroute the user away to another route, which is the /homepage
route. I was wondering if this is an ok thing to do in React or not. Please see code below:
renderWithRoot(component) {
const { classes, profileExists, history } = this.props;
if (profileExists === false) {
history.push('/homepage');
}
return (
<div className={classes.root}>
{component}
</div>
);
}
CodePudding user response:
It is ok, but not quite in the way you are using it. You should either issue the redirect as an imperative navigation in a useEffect
hook
useEffect(() => {
if (!profileExists) {
history.replace('/homepage');
}
}, [profileExists]);
...
return (
<div className={classes.root}>
{component}
</div>
);
or issue the redirect as a declarative navigation via rendering the Redirect
component.
if (!profileExists) {
return <Redirect to='/homepage' />;
}
return (
<div className={classes.root}>
{component}
</div>
);