I am getting this Type Error in one of my component in which i want to redirect users on load
based on conditions
ex- If user is not login redirect him to login page
import { useHistory } from 'react-router';
const someCompo = () => {
const history = useHistory();
if(!user) return history.push('/login');
return(<div>...component </div>)
}
export default someCompo;
but when i test this component in render of react-testing library. i am getting this type error
In .test File
import { render, screen } from '@testing-library/react';
import someCompo from '../someCompo ';
it('Check Redirect', () => {
render(<someCompo />)
}
But when I use Redirect it doesn't show error
if (!user) return <Redirect to='/login'/>
Can someone please explain why it's giving me a error
CodePudding user response:
you cant return void
as an element. and if you want to do something like this it would be better to use the useEffect
import { useHistory } from 'react-router';
const someCompo = ({ user }) => {
const history = useHistory();
useEffect(() => {
if(!user) {
history.push('/login');
}
}, [user]);
if(!user) return null;
return <div>...component </div>;
}
export default someCompo;
return history.push('/login')
will return void
, as history.push('/login')
will return void
. and void
is not a valid react element.
the ugly way without useEffect hook would be:
import { useHistory } from 'react-router';
const someCompo = ({ user }) => {
const history = useHistory();
if(!user) {
history.push('/login');
return null;
}
return <div>...component </div>;
}
export default someCompo;