How to use media queries in React.js?

Member

by lily , in category: Javascript , a year ago

How to use media queries in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 10 months ago

@lily 

To use media queries in React.js, you can follow these steps:

  1. Import the 'useMediaQuery' hook from the 'react-responsive' library. import { useMediaQuery } from 'react-responsive';
  2. Define your media query using the 'useMediaQuery' hook. You can pass the media query string as a parameter to this hook. const isMobile = useMediaQuery({ query: '(max-width: 767px)' }); In the above example, the 'isMobile' variable will be true if the screen width is less than or equal to 767 pixels. You can also provide multiple media queries as an array: const isMobile = useMediaQuery([{ query: '(max-width: 767px)' }, { query: '(max-height: 500px)' }]); In the above example, the 'isMobile' variable will be true if the screen width is less than or equal to 767 pixels or the screen height is less than or equal to 500 pixels.
  3. Use the 'isMobile' variable to conditionally render components or apply different styles. return ( ); In the above example, the 'MobileComponent' will be rendered if the 'isMobile' variable is true, otherwise the 'DesktopComponent' will be rendered.


By using media queries and the 'useMediaQuery' hook in React.js, you can easily create responsive designs and adjust the behavior and appearance of your application based on the screen size.