Unable to pass property value of ReactJS component to another component
P粉647504283
P粉647504283 2023-08-16 00:30:36
0
1
445

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.

**Home.js component** const Home = () => { const [heightNav, setHeightNav] = useState(0); useEffect(() => { console.log(heightNav); }, [heightNav]); return ( 
{ setHeightNav(() => h); }} />
); }; **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 ( ); };
P粉647504283
P粉647504283

reply all (1)
P粉420958692

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 
Navbar Content
; }; export default Navbar;
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!