22 August 2024

You can create a Preact component that rerenders every time the window is resized by using window.addEventListener('resize'). The general approach involves setting up an event listener in a useEffect hook, and then triggering a state update in the component whenever the resize event occurs. This will cause the component to rerender.

Source code viewer
  1. import { h } from 'preact';
  2. import { useState, useEffect, useRef } from 'preact/hooks';
  3.  
  4. const ResizeComponent = ({ countArray }) => {
  5. const [width, setWidth] = useState(window.innerWidth);
  6. const divRef = useRef(null);
  7.  
  8. // Resize handler function
  9. const handleResize = () => {
  10. setWidth(window.innerWidth);
  11.  
  12. // Ensure the ref is initialized before accessing it
  13. if (divRef.current) {
  14. // You can perform any action on the DOM element here
  15. divRef.current.textContent = `Window width is ${window.innerWidth}px`;
  16. }
  17. };
  18.  
  19. // Effect for setting up the resize event listener
  20. useEffect(() => {
  21. window.addEventListener('resize', handleResize);
  22.  
  23. // Trigger the resize handler initially to set the text content
  24. handleResize();
  25.  
  26. // Cleanup the event listener on component unmount
  27. return () => {
  28. window.removeEventListener('resize', handleResize);
  29. };
  30. }, []); // Empty dependency array means this effect runs once on mount
  31.  
  32. // Effect to trigger the resize handler when countArray changes
  33. useEffect(() => {
  34. handleResize();
  35. }, [countArray]); // Dependency array includes countArray
  36.  
  37. return (
  38. <div>
  39. <p ref={divRef}>Window Width: {width}px</p>
  40. <p>Array Count: {countArray.length}</p>
  41. </div>
  42. );
  43. };
  44.  
  45. export default ResizeComponent;
Programming Language: ECMAScript