React-spring useSpring() prevents viewport size from updating when window is resized Code Answer

I have made a simple animation with a search bar using react-spring’s useSpring(). When in focus, I want the search bar to change width, change its margin to 0, and change its top value to 0.

The first issue I encounter is that the margin does not change. I don’t know if this is an issue with the auto keyword, but the search bar is centred before the animation, and doesn’t change.

The second issue is that when I resize the window, the top value and width value of the search bar (which are in units of vw and vh) don’t update until the page is refreshed, or the search bar goes back into focus.

I’ve linked my code here

Will I need to make the app auto-refresh on window resize to fix this?

Answer

For the first part, try using other method of centering than margin: auto. For example with a combination of left: 50%; transform: translateX(-50%) you can also center your component. And react-spring can interpolate with this values.

For the second part. Try using viewport units instead of pixels. Like vw and vh.

Something like this:

  const props = useSpring({
    top: focused ? `0px` : `${0.29 * window.innerHeight - 35}px`,
    width: focused
      ? `80vw`
      : `50vw`,
    margin: '10px',
    left: focused ? '40%' : '50%',
    transform: 'translateX(-50%)',
    config: { velocity: 4, mass: 1.8 }
  });

Full example: https://codesandbox.io/s/react-spring-browser-resizing-mm7d1

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji