The next.js styled-components does not work when opened in the mobile browser

  Kiến thức lập trình

i’m using next.js, emotion/styled, ‘react-responsive’ in my project.

when running on a desktop browser, the style works normally.
The style works normally even if it’s re-rendered like page switching.

when running on a mobile browser, the style does not apply.

i’m using meta tag

// rootLayout.jsx
import Head from "next/head"

    <meta name="viewport" content="width=device-width, initial-scale=1" />

I want to know what the problem is. ????????
The code I used is as follows.

my code **

  • mediaquery custom hook
import { useMediaQuery } from "react-responsive"

export const useIsMobile = () => {
  const isMobile = useMediaQuery({ query: "(max-width: 767px)" })
  return isMobile
  • Issue.tsx
import { useIsMobile } from "@/hooks/useMediaQuery"
export default function Issue() {
  const isMobile = useIsMobile()
  return (
    <Div isMobile={isMobile}>
const Div = styled.div<{ isMobile?: boolean }>`
  background-color: #eaeaea;
  padding: ${(props) => (props.isMobile ? "20px" : "0")}; // 20px not applied in mobile browser

// my version in package.json

“dependencies”: {
“@emotion/react”: “^11.11.3”,
“@emotion/styled”: “^11.11.0”,
“@fontsource/noto-sans”: “^5.0.18”,
“next”: “14.0.4”,
“react”: “^18”,
“react-dom”: “^18”,
“react-responsive”: “^9.0.2”

The method I used to solve this problem :

** 1. Rendering components after mount**
In this method, the style works normally.
But there is a problem that I have to use all of the components in the problem.

  const [isMount, setIsMount] = useState(false)

  useEffect(() => {
  }, [])

  if (!isMount) return null

2. Modifying media query hook
This method causes the browser to flicker

export const useIsMobile = () => {
  const [isMount, setIsMount] = useState(false)
  const isMobile = useMediaQuery({ query: "(max-width: 767px)" })

  useEffect(() => {
  }, [])

  return isMount ? isMobile : undefined

thank you

New contributor

ramin5 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.