Reputation: 11
I'm trying to assign a value to a variable depending on the viewport size using Hooks in Gatsby I'm using nested conditionals and it works when I test the webpage for the first time but if I resize manually the window browser it displays the following error:
Rendered fewer hooks than expected. This may be caused by an accidental early return statement
As the react Docs says: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. So I tried using a ternary operation:
let filter = (useMediaQuery({ query: '(max-width: 695px)' })) ? 2 : (useMediaQuery({ query: '(min-width: 900px)' })) ? 4 : 3
I also tried with:
if (useMediaQuery({ query: '(max-width: 695px)' }))
{ filter = 2 } else if (useMediaQuery({ query: '(max-width: 900px)' }))
{ filter = 4 } else { filter = 3 }
Could you help me, please?
Upvotes: 0
Views: 203
Reputation: 4741
According to the rules of hooks, all hooks should be called at the top level of a component.
export function YourComponent() {
const isSmallFormFactor = useMediaQuery({ query: '(max-width: 695px)' });
const isMediumFormFactor = useMediaQuery({ query: '(max-width: 900px)' });
const filter = isSmallFormFactor
? 2
: isMediumFormFactor
? 4
: 3;
return (
// ...
);
}
Upvotes: 1