This should be an easy one for you React monsters. :) I have the condition written but I can\'t figure out how to handle the viewport size in my constructor for the condition to
the issue with your code is that it only works if the resizing happens, here I have the handleWindowResiz
function will set the width to the window.innerWidth
and compares it to the breakPoint
to conditionally render your UI, if the user resizes the screen the event listener will be triggered and the handleWindowResiz
will be called and it will reset the width
to the new window.innerWidth
and you get your desired UI. So the UI is always rendered correctly when the component is first rendered and when the user resizes the screen width.
const MyFunction = () => {
const [width, setWidth] = React.useState(window.innerWidth);
const breakPoint = 1450;
useEffect(() => {
const handleWindowResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", handleWindowResize);
return () => window.removeEventListener("resize", handleWindowResize);
},[]);
return (
{width > breakPoint? (
I show on 1451px or higher
) : (
I show on 1450px or lower
)}
);
}