Home  >  Q&A  >  body text

Unable to pass property value of ReactJS component to another component

<p>How to get the latest updated value of the dimensions object in the Navbar.js component in the Home.js component? I tried passing a callback function as props from Home.js to Navbar.js (since Home.js is the parent component of Navbar.js), but I cannot store the newly updated dimensions state value in Navbar.js. If I pass the dimensions state as a dependency of useEffect, it causes an infinite loop. please help me. </p> <pre class="brush:php;toolbar:false;">**Home.js component** const Home = () => { const [heightNav, setHeightNav] = useState(0); useEffect(() => { console.log(heightNav); }, [heightNav]); return ( <div> <Navbar setHeight={(h) => { setHeightNav(() => h); }} /> </div> ); }; **Navbar.js component** const Navbar = ({ setHeight }) => { const refContainer = useRef(); const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); useEffect(() => { if (refContainer.current) { setDimensions(() => { return { width: refContainer.current.offsetWidth, height: refContainer.current.offsetHeight, }; }); setHeight(dimensions.height); } }, []); return ( <Container ref={refContainer}> </Container> ); };</pre>
P粉647504283P粉647504283403 days ago468

reply all(1)I'll reply

  • P粉420958692

    P粉4209586922023-08-16 22:15:16

    Try this navigation bar:

    import React, { useEffect, useState, useRef } from 'react';
    
    const Navbar = ({ setHeight }) => {
      const refContainer = useRef();
      const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
    
      useEffect(() => {
        const updateDimensions = () => {
          if (refContainer.current) {
            setDimensions({
              width: refContainer.current.offsetWidth,
              height: refContainer.current.offsetHeight,
            });
          }
        };
    
        updateDimensions();
        window.addEventListener('resize', updateDimensions);
    
        return () => {
          window.removeEventListener('resize', updateDimensions);
        };
      }, []);
    
      useEffect(() => {
        setHeight(dimensions.height);
      }, [dimensions.height, setHeight]);
    
      return <div ref={refContainer}>Navbar Content</div>;
    };
    
    export default Navbar;

    reply
    0
  • Cancelreply