Sometimes, we want to conditionally render items based on viewport size in React.
In this article, we’ll look at how to conditionally render items based on viewport size in React.
How to conditionally render items based on viewport size in React?
To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window
.
For instance, we write:
import React, { useState, useEffect } from "react";
export default function App() {
const [isDesktop, setDesktop] = useState(window.innerWidth > 650);
const updateMedia = () => {
setDesktop(window.innerWidth > 650);
};
useEffect(() => {
window.addEventListener("resize", updateMedia);
return () => window.removeEventListener("resize", updateMedia);
});
return (
<div>
{isDesktop ? (
<div>I show on 651px or higher</div>
) : (
<div>I show on 650px or lower</div>
)}
</div>
);
}
We create the isDesktop
state which is set to window.innerWidth > 650
initially.
Then we define the updateMedia
function that calls setDesktop
with window.innerWidth > 650
.
Then we call useEffect
with a callback that attaches the resize event listener to window
with addEventListener
.
We use updateMedia
as the resize event listener.
In updateMedia
, we call setDesktop
with window.innerWidth > 650
to check if we’re in a desktop sized screen.
Also, we return a function to calls window.removeEventListener
to clear the event listener.
Finally, we render the content we want based on the value of isDesktop
.
Conclusion
To conditionally render items based on viewport size in React, we can listen to the resize event emitted by window
.