Home > Enterprise >  Styled-components: Style not updated after switching from mobile
Styled-components: Style not updated after switching from mobile

Time:06-02

Here:

  • Open the app in desktop width, notice the div has green background
  • Reduce browser width to mobile, the div background should change to gray
  • Again, increase browser width to desktop, notice the gray background remains, instead of green

What should have happened

  • The background in last step should be green as in the first step, isn't it?

Logging value of isMobile does seem to show it is being updated.


Here is also code:

import React from 'react';
import styled from 'styled-components';
import { useMediaQuery } from 'react-responsive';

let MenuItem = styled.div`
  height: 100px;
  width: 100px;
  border:1px solid red;
  background-color: green;
 

  // Select those items which are children of .submenu
  .submenu & {
    background-color: ${({ isMobile }) => {
      return isMobile && 'lightgray';
    }};
  }

   
`;

function App() {
  const isMobile = useMediaQuery({ query: '(max-width: 524px)' });

  return (
    <div>
      <div className="submenu">
        <MenuItem isMobile={isMobile}>test</MenuItem>
      </div>
    </div>
  );
}

export default App;

CodePudding user response:

    import React, {useEffect, useState} from 'react';
    import styled from 'styled-components';
    import {useMediaQuery} from 'react-responsive';
    
    let MenuItem = styled.div`
      height: 100px;
      width: 100px;
      border:1px solid red;
      background-color: green;
    `;
    
    function App() {
        const isMobile = useMediaQuery({query: '(max-width: 524px)'});
        const [color, setColor] = useState('green');
    
        useEffect(() => {
            if (isMobile) setColor('silver');
            else setColor('green');
        }, [isMobile])
        return (
            <div>
                <div className="submenu">
                    <MenuItem style={{background: color}} isMobile={isMobile}>test</MenuItem>
                </div>
            </div>
        );
    }

export default App;

CodePudding user response:

You could re-write this as:

const MenuItem = styled.div` 
      height: 100px;
      width: 100px;
      border:1px solid red;
      background-color: green;
    `;

const SubMenu = styled.div`
  ${MenuItem} {
    background-color: ${({ isMobile }) => (isMobile ? `red` : 'lightgray')};
  }
  `;

function App() {
  const isMobile = useMediaQuery({ query: '(max-width: 524px)' });
  return (
    <>
      <SubMenu isMobile={isMobile}>
        <MenuItem>MenuItem in SubMenu</MenuItem>
      </SubMenu>
      <MenuItem>MenuItem</MenuItem>
    </>
  );
}

Stackblitz

CodePudding user response:

It is the correct answer:

https://stackblitz.com/edit/react-t7gqwx?file=src/App.js,src/index.js

You shouldn't use .submenu &.

  • Related