'I cannot optimize the design for the mobile version

There is my code. I try to change styles through props but nothing comes out, I do it to optimize the design for phones.

On Navbar.jsx

import { Search, ShoppingCartOutlined } from "@mui/icons-material";
import { Badge } from "@mui/material";
import React from "react";
import styled from "styled-components";
import { mobile } from "../pages/responsive";

const Container = styled.div`
  height: 60px;
  ${mobile({ height: "50px" })}
`;

const Wrapper = styled.div`
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  ${mobile({ padding: "10px 0px" })}
`;
const Left = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
`;

const Language = styled.span`
  font-size: 14px;
  cursor: pointer;
  ${mobile({ display: "none" })}
`;

On responsive.jsx

    import {cssx from "styled-components"

export const mobile = (props) => {
    return css `
        @media only screen and (max-width: 380px) {
            ${props}
    }
    `;
};

Styles do not change, maybe I spelled the props wrong?



Solution 1:[1]

You can do this by using a media query. The query can be adjusted to look out for a specific size (380px), or certain breakpoints (lg, md, etc.).

All-in-one external library:

useMediaQuery from MUI is easy to use and reliable. Below is a simple example that is watching for 380px screen size.

import * as React from 'react'
import useMediaQuery from '@mui/material/useMediaQuery'

export default function SimpleMediaQuery()
{
  const matches = useMediaQuery('(min-width:380px)')

  return <span>{`(min-width:380px) matches: ${matches}`}</span>
}

Want to use the preset breakpoints instead?

const matches = useMediaQuery(theme.breakpoints.up('sm'))

Callback?

const matches = useMediaQuery((theme) => theme.breakpoints.up('sm'))

This hook can be customized in multiple ways (see the docs linked above for more examples).


Custom hook with no external libraries:

If you want to do it without relying on an external library, here is a simple hook that watches for certain breakpoints, similar to MUI's useMediaQuery.

export const useMediaQuery = (width) =>
{
  const [targetReached, setTargetReached] = useState(false)

  const updateTarget = useCallback((e) =>
  {
    if (e.matches) setTargetReached(true)
    else setTargetReached(false)
  }, [])

  useEffect(() =>
  {
    const media = window.matchMedia(`(max-width: ${width}px)`)
    media.addEventListener('change', updateTarget)

    // Check on mount (callback is not called until a change occurs)
    if (media.matches) setTargetReached(true)

    return () => media.removeEventListener('change', updateTarget)
  }, [])

  return targetReached
}

Usage:

// 380px
const matches = useMediaQuery(380)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pez