Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3095 | Mostrar el archivo completo | | | Autoría | Ultima modificación | Ver Log |

Rev 3095 Rev 3719
Línea 1... Línea 1...
1
import { useLayoutEffect, useState } from 'react'
1
import { useLayoutEffect, useState } from 'react';
2
 
2
 
3
export function useMediaQuery(
-
 
4
  query,
-
 
5
  options = { defaultValue: false, initializeWithValue: true }
3
export function useMediaQuery(query, options = { defaultValue: false, initializeWithValue: true }) {
6
) {
-
 
7
  const getMatches = (query) => {
4
  const getMatches = (query) => {
8
    return window.matchMedia(query).matches
5
    return window.matchMedia(query).matches;
9
  }
6
  };
10
 
7
 
11
  const [matches, setMatches] = useState(() => {
8
  const [matches, setMatches] = useState(() => {
12
    if (options.initializeWithValue) {
9
    if (options.initializeWithValue) {
13
      return getMatches(query)
10
      return getMatches(query);
14
    }
11
    }
15
    return options.defaultValue
12
    return options.defaultValue;
16
  })
13
  });
17
 
14
 
18
  // Handles the change event of the media query.
15
  // Handles the change event of the media query.
19
  function handleChange() {
16
  function handleChange() {
20
    setMatches(getMatches(query))
17
    setMatches(getMatches(query));
21
  }
18
  }
22
 
19
 
23
  useLayoutEffect(() => {
20
  useLayoutEffect(() => {
24
    const matchMedia = window.matchMedia(query)
21
    const matchMedia = window.matchMedia(query);
25
    handleChange()
22
    handleChange();
26
 
23
 
27
    matchMedia.addEventListener('change', handleChange)
24
    matchMedia.addEventListener('change', handleChange);
28
    return () => {
25
    return () => {
29
      matchMedia.removeEventListener('change', handleChange)
26
      matchMedia.removeEventListener('change', handleChange);
30
    }
27
    };
31
  }, [query])
28
  }, [query]);
32
 
29
 
33
  return matches
30
  return matches;
34
}
31
}