Then we call window.addEventListener with 'resize' to set updateSize as the window resize event listener.Īlso, we return a function that calls window.removeEventListener to clear the resize event listener when the component unmounts. We can also use the height and width attributes on the img tag directly. Because resizing is async, one trick with React is to make the children into a functional return instead of just returning JSX. Resizing images in React is very similar to resizing images in traditional HTML because we use CSS styles (either internal, inline, or external styling) via className or the style attribute. The advantage is it can be used again for something else. In the useLayoutEffect hook callback, we create the updateSize function that calls setSize to set thje size state to an array with window.innerWidth and window.innerHeight, which has the width and height of the browser window respectively. Personally I would extract out the part of listening for resize events. react-resize-aware is a zero dependency, 600 bytes React Hook you can use to. We create the useWindowSize hook that has the size state. It does one thing, it does it well: listens to resize events on any HTML element. Return () => window.removeEventListener("resize", updateSize) Window.addEventListener("resize", updateSize) We can use the useLayoutEffect to add the event listener that runs when the window resizes.Īnd in the window resize event handler, we can run our code to change a state to make the view rerender.įor instance, we can write: import React, from "react" Ĭonst = useState() Description: Bind an event handler to the resize JavaScript event, or trigger that event on an element. Rerender the View on Browser Resize with React To resize images in React, developers use CSS properties like min-height, max-height, min-width, and max-width.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |