Как использовать компонент useMediaQuery в ReactJS?

Опубликовано: 8 Августа, 2022

Компонент useMediaQuery — это хук медиа-запроса CSS для React . Используя эту функциональность, мы можем написать собственный медиа-запрос CSS, для которого эта функция ищет совпадения и выполняет рендеринг, если запрос совпадает. Материал UI для React имеет этот компонент, доступный для нас, и его очень легко интегрировать. Мы можем использовать следующий подход в ReactJS для использования компонента useMediaQuery.

Создание приложения React и установка модуля:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername
  • Step 3: After creating the ReactJS application, Install the material-ui module using the following command:

    npm install @material-ui/core/useMediaQuery
  • Project Structure: It will look like the following.

    Project Structure

    Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

    App.js




    import React from "react";
    import useMediaQuery from "@material-ui/core/useMediaQuery";
      
    export default function App() {
      const ourMediaQuery = useMediaQuery("(min-width:400px)");
      return (
        <div style={{ display: "block"}}>
          <h4>How to use useMediaQuery Component in ReactJS?</h4>
          <span>{`Is Screen at Minimum 400px: ${ourMediaQuery}`}</span>
        </div>
      );
    }

    Step to Run Application: Run the application using the following command from the root directory of the project:

    npm start

    Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

    Reference: https://material-ui.com/components/use-media-query/

РЕКОМЕНДУЕМЫЕ СТАТЬИ