I want to get windowsize of the browser and according to this condition I want to render something in the component. When I try to get clientWidth using useEffect, I get the value. However, I can not assign it the variable which I defined it in useState.
This is my code. and sometimes I'm getting the following error which I don't understand because I don't assign anything to constant variable. I try to assign variable of useState.
import React, { useState, useEffect } from 'react';
export default function App() {
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
if (document.documentElement.clientWidth <= 400) {
console.log(document.documentElement.clientWidth);
setIsMobile = true;
}
}, []);
return (
<div>
{(() => {
console.log(isMobile);
if (isMobile === true) {
return <div>This is Mobile</div>;
} else {
return <div>This is normal</div>;
}
})()}
</div>
);
}
And this is the written version in stackblitz.
https://stackblitz.com/edit/react-i9ewp6?file=src/App.js
CodePudding user response:
You are trying to assign a value to the setIsMobile
state updater function, which is declared const, so you can't reassign a value to it anyway. You need to call the function with the value you want to update state to.
useEffect(() => {
if (document.documentElement.clientWidth <= 400) {
console.log(document.documentElement.clientWidth);
setIsMobile(true);
}
}, []);
or more succinctly
useEffect(() => {
setIsMobile(document.documentElement.clientWidth <= 400);
}, []);
Since isMobile
is a boolean value, it's considered anti-pattern to compare it against true
|false
, just use its "boolean-ness" directly.
return (
<div>
{isMobile ? (
<div>This is Mobile</div>
) : (
<div>This is normal</div>
)}
</div>
);
Also, if you want to log values do it in an useEffect
hook as an intentional side-effect.
useEffect(() => {
console.log(isMobile);
}, [isMobile]);