Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

react get screen width

// useWindowDimensions.js

import { useState, useEffect } from 'react';

export default function useWindowDimensions() {

  const hasWindow = typeof window !== 'undefined';

  function getWindowDimensions() {
    const width = hasWindow ? window.innerWidth : null;
    const height = hasWindow ? window.innerHeight : null;
    return {
      width,
      height,
    };
  }

  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    if (hasWindow) {
      function handleResize() {
        setWindowDimensions(getWindowDimensions());
      }

      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }
  }, [hasWindow]);

  return windowDimensions;
}

// yourComponent.js

import useWindowDimensions from './hooks/useWindowDimensions';

const Component = () => {
  const { height, width } = useWindowDimensions();
  /* you can also use default values or alias to use only one prop: */
  // const { height: windowHeight = 480 } useWindowDimensions();

  return (
    <div>
      width: {width} ~ height: {height}
    </div>
  );
Comment

react js get screen size

  console.log(window.innerHeight);
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript sort chars in string 
Javascript :: regex find lines containing two strings 
Javascript :: create react app node 12 
Javascript :: jquery how to know if element is visible 
Javascript :: react-native release build 
Javascript :: post antiforgerytoken jquery 
Javascript :: how to check if input file is empty in jquery 
Javascript :: discord javascript error cannot find module 
Javascript :: jest reset spy 
Javascript :: wordpress header script add 
Javascript :: how to run angular 
Javascript :: jquery on click get element 
Javascript :: jquery grid get all selected row 
Javascript :: react router get host origin js 
Javascript :: javascript get highlighted text 
Javascript :: json nuget package manager 
Javascript :: javascript convert number to string 
Javascript :: javascript window alert 
Javascript :: javascript group by on array of objects 
Javascript :: javascript check if undefined or null 
Javascript :: how to get date time day year in javscript 
Javascript :: how to sum array elements in javascript 
Javascript :: use emmet autocomplete with jsx vs code 
Javascript :: how to find the key of an value in an object 
Javascript :: jquery loop through list element 
Javascript :: convert dict to json python 
Javascript :: fontawesome in next js 
Javascript :: translatex in javascript 
Javascript :: js refresh button 
Javascript :: exceljs read file from input 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =