Introduction
This article covers the following tech skills:
In this lab, we will explore the use of the useMediaQuery
hook in React. This hook allows us to check if the current environment matches a given media query and return the appropriate value. We will learn how to use this hook to create responsive components that change their behavior based on the screen size.
React useMediaQuery Hook
index.html
andscript.js
have already been provided in the VM. In general, you only need to add code toscript.js
andstyle.css
.
This function checks if the current environment matches a given media query and returns the appropriate value.
- First, check if
Window
andWindow.matchMedia()
exist. If not (e.g. in an SSR environment or unsupported browser), returnwhenFalse
. - Use
Window.matchMedia()
to match the givenquery
. Cast itsmatches
property to a boolean and store it in a state variable,match
, using theuseState()
hook. - Use the
useEffect()
hook to add a listener for changes and to clean up the listeners after the hook is destroyed. - Finally, return either
whenTrue
orwhenFalse
based on the value ofmatch
.
const useMediaQuery = (query, whenTrue, whenFalse) => {
if (
typeof window === "undefined" ||
typeof window.matchMedia === "undefined"
) {
return whenFalse;
}
const mediaQuery = window.matchMedia(query);
const [match, setMatch] = React.useState(!!mediaQuery.matches);
React.useEffect(() => {
const handler = () => setMatch(!!mediaQuery.matches);
mediaQuery.addListener(handler);
return () => mediaQuery.removeListener(handler);
}, [mediaQuery]);
return match ? whenTrue : whenFalse;
};
const ResponsiveText = () => {
const text = useMediaQuery(
"(max-width: 400px)",
"Less than 400px wide",
"More than 400px wide"
);
return <span>{text}</span>;
};
ReactDOM.createRoot(document.getElementById("root")).render(<ResponsiveText />);
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the React useMediaQuery Hook lab. You can practice more labs in LabEx to improve your skills.
Want to learn more?
- ๐ Practice React useMediaQuery Hook
- ๐ณ Learn the latest React Skill Trees
- ๐ Read More React Tutorials
Join our Discord or tweet us @WeAreLabEx ๐
Top comments (0)