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;