custom Hook useMediaQuery
This commit is contained in:
@@ -1,8 +1,13 @@
|
|||||||
import { useFetch } from "../../hooks/useFetch";
|
import { useFetch } from "../../hooks/useFetch";
|
||||||
|
import { useMediaQuery } from "../../hooks/useMediaQuery";
|
||||||
|
|
||||||
export function UserOverview() {
|
export function UserOverview() {
|
||||||
const {data, loading, error} = useFetch("https://jsonplaceholder.typicode.com/users");
|
const {data, loading, error} = useFetch("https://jsonplaceholder.typicode.com/users");
|
||||||
|
|
||||||
|
const isMobile = useMediaQuery('(max-width: 600px)');
|
||||||
|
|
||||||
|
console.log("isMobile", isMobile);
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return <p>Error: {error}</p>;
|
return <p>Error: {error}</p>;
|
||||||
}
|
}
|
||||||
@@ -18,7 +23,7 @@ export function UserOverview() {
|
|||||||
<ul>
|
<ul>
|
||||||
{data.map((user: { id: number; name: string; email: string; website: string }) => (
|
{data.map((user: { id: number; name: string; email: string; website: string }) => (
|
||||||
<li key={user.id}>
|
<li key={user.id}>
|
||||||
<strong>{user.name}</strong> ({user.email}) - {user.website}
|
<strong>{user.name}</strong> <div style={{display: isMobile ? 'none' : 'block' }}>({user.email}) - {user.website}</div>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
31
react-advanced-tag1/src/hooks/useMediaQuery.ts
Normal file
31
react-advanced-tag1/src/hooks/useMediaQuery.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom hook to check if a media query matches the current viewport.
|
||||||
|
* @param query - The media query string (e.g., '(max-width: 600px)')
|
||||||
|
* @returns A boolean indicating whether the media query matches.
|
||||||
|
*/
|
||||||
|
export function useMediaQuery(query: string) {
|
||||||
|
const [matches, setMatches] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const mediaQueryList = window.matchMedia(query);
|
||||||
|
const handleChange = (event: MediaQueryListEvent) => {
|
||||||
|
setMatches(event.matches);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Set the initial value
|
||||||
|
setMatches(mediaQueryList.matches);
|
||||||
|
|
||||||
|
// Add event listener
|
||||||
|
mediaQueryList.addEventListener('change', handleChange);
|
||||||
|
|
||||||
|
// Cleanup function to remove the event listener
|
||||||
|
return () => {
|
||||||
|
mediaQueryList.removeEventListener('change', handleChange);
|
||||||
|
};
|
||||||
|
}, [query]);
|
||||||
|
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user