Styled-components not updating with prop change

Viewed 513

I am using styled-components with Gatsby and trying to make a fullscreen hero for the homepage which does not get covered by the navigation bar on mobile devices. I am trying to achieve this by resizing the height of the image to window.innerHeight when the page has loaded.

The code I am using to do this is:

const HeightlessHero = styled(BackgroundImage)`
  width: 100%;
  height: ${props => props.realHeight};`

const HeroImage = (props) => {
  const [height, setHeight] = useState('100vh');

  useEffect(() => {
    setHeight(window.innerHeight+'px');
  }, [window.innerHeight]);

  return <HeightlessHero {...props} realHeight={height} />;
}

This unfortunately does not work, keeping the initial height in the useState. However, the state itself is updating successfully when I check the dev tools.

The code below on the other hand does work successfully, but is as far as I'm aware not a good way to write React.


const HeroImage = (props) => {
  const [height, setHeight] = useState('100vh');
  const HeightlessHero = styled(BackgroundImage)`
    width: 100%;
    height: ${props => props.realHeight};`

  useEffect(() => {
    setHeight(window.innerHeight+'px');
  }, [window.innerHeight]);

  return <HeightlessHero {...props} realHeight={height} />;

So, the question is, why does the first example not work and how can I make it work?

0 Answers
Related