Unable to pass property value of ReactJS component to another component
P粉647504283
2023-08-16 00:30:36
<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>
Try this navigation bar: