Styled-components' styles fail to update after transitioning from mobile view

Click here to view the app:

  • When you open the app in desktop width, you will see that the div has a green background.
  • If you reduce the browser width to mobile size, the background of the div should change to gray.
  • Now, if you increase the browser width back to desktop size, you may notice that the gray background remains instead of changing back to green.

What do you think should have happened?

  • In the last step, shouldn't the background color be green again as it was in the first step?

Even though the value of isMobile seems to update, the background color doesn't reflect this change as expected.


Below is the code snippet for reference:

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;    

  .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;

Answer №1

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

export default MyApp;

Answer №2

Here is a revised version:

const ButtonItem = styled.div` 
      height: 100px;
      width: 100px;
      border:1px solid blue;
      background-color: yellow;
    `;

const Dropdown = styled.div`
  ${ButtonItem} {
    background-color: ${({ isDesktop }) => (isDesktop ? `blue` : 'lightyellow')};
  }
  `;

function Main() {
  const isDesktop = useMediaQuery({ query: '(min-width: 768px)' });
  return (
    <>
      <Dropdown isDesktop={isDesktop}>
        <ButtonItem>ButtonItem in Dropdown</ButtonItem>
      </Dropdown>
      <ButtonItem>ButtonItem</ButtonItem>
    </>
  );
}

Stackblitz

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I create clickable table entries using php and html?

I want to create a table on this page that is clickable. When the user clicks on a row, the data from that row will be sent to a PHP file with a form prepopulated with the selected user's information for updating purposes. <!DOCTYPE html> &l ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

Building a Carousel Component in NextJS

I've been trying to create a carousel similar to the one on Amazon's homepage. I attempted to use React Bootstrap for this, but unfortunately, it doesn't seem to be working as expected. Instead of displaying items in a carousel format, they ...

Is there a way to create a table that has varying columns for each row?

I am currently working with bootstrap4 and I am trying to create a table that has 3 columns in the first row and 4 columns in the following two rows. I want it to look like this: https://i.sstatic.net/nuI55.png Here is my existing table: <link href ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

Having issues with npx create-react-app not functioning properly due to everything being flagged as deprecated

Today, when I try to run the command npx create-react-app project-name, I am encountering a series of errors as shown below. I have attempted to resolve the issue by clearing the cache, reinstalling node, and removing npx create-react-app globally... npm ...

Exploring a section of a react-chartjs Pie chart

I'm currently exploring how to create a static Pie chart using react-chartjs-2. Wanting to make one slice stand out more than the others, I aim to have it appear larger: https://i.sstatic.net/rRTvN.png My focus is on accessing a specific slice in th ...

CSS Issue: Hovering Over Link Causes Text to Shift in Internet Explorer

Encountering a problem with CSS and IE, specifically in Internet Explorer 9. When hovering over certain links, the text shifts down which does not occur when using Firefox. You can see an example of this issue at: http://www.debtdispatch.com/list_item_err ...

What is your preferred method for adjusting the size of Divs on your webpage according to the screen size?

Currently working on a coding test and facing an issue with the display of div sizes across different screens. The discrepancy in appearance between my laptop and a Mac computer monitor is causing some trouble, as on my small laptop the divs appear overs ...

Is there a way to prevent EasyTabs from automatically selecting the second tab?

I'm facing an issue with setting the default tab using easytabs. Currently, the second option is automatically selected as the default tab. Previously, I had successfully set the first tab (statistics) as the active tab but lost the file. Now, I am s ...

Creating a responsive YouTube video embed within a div container with a fixed background image

Hello there, I'm currently working on positioning the YouTube Iframe on the background to make it look like the video is playing on a laptop screen. I also want it to scale down appropriately with the background image on different resolutions. The w ...

The <img> tag is displaying with dimensions of 0 x 0 pixels even though its size was specified

Is there a way to control the image size within an <img> tag placed inside an html5 video element? Currently, it keeps defaulting back to 0 x 0 pixels. The reason behind using this img is to serve as a fallback for outdated browsers where the video ...

React - Issue with useState not displaying updated values

I am attempting to link a user-entered value to another input field that is read-only. However, the value is also showing up in other input fields. Although I can see the value on the HTML page as I type, I am struggling to connect it to the desired input. ...

Guide on integrating React with Node.js and HTML

I've tried various methods, searched on Google, and checked the official site, but nothing seems to work. The code only functions properly when I include it in the HTML file of node.js like this: <!DOCTYPE html> <html lang="en"& ...

We encountered an issue loading the resource: the server has returned a 404 (Not Found) error message and a 403 Forbidden error message. However, the resource functions properly on Codepen and localhost

I have a CodePen demo that works fine. However, when I upload it to the server, it stops working properly and most external references show 404 errors. Initially, there were no problems, but now it seems to be an issue like this: !--> http://sachin.ipov ...

Encountering a Next.js Redux Persist Issue - SyntaxError: Unable to utilize import statement in an external module

I encountered an issue while attempting to implement persistReducer in my Next.js project, leading to the following error: error - SyntaxError: Cannot use import statement outside a module /Users/xx/node_modules/redux-persist/es/persistReducer.js:11 ...

Issue with JQUERY where HTML select element is not visible

$(document).ready(function(){ var selArr = [ {val: 'corsair', text: 'Corsair'}, {val: 'evga', text: 'EVGA'}, {val: 'antec', text: 'Antec'} ]; $('#pSupply& ...

Combine the points of individual letters in Scrabble using jQuery

Hello, I'm currently working on creating a Scrabble game. My goal is to assign a value to each letter and then calculate the sum of these values when the input box changes. After some research, I was able to find information on how to add numbers on ...

Having difficulty aligning the button in the center

I encountered an issue trying to center a button, I attempted to use text-align: center, but it didn't have the desired effect. .regis-btn { border-radius: 0px; text-align: center; -moz-border-radius: 10px; -webkit-border-radius: 10px; -o ...