I want to make a specific calculation in Search component. To do this, I have to pass a buttonSearchRefOffsetLeftValue obtained in the Header component to a Search component. I get the desired value in the Header. However in the Search component it always gets undefined. Can't understand this behavior.
const Header = props => {
const buttonSearchRef = useRef(null);
let buttonSearchRefOffsetLeftValue;
useEffect(() => {
buttonSearchRefOffsetLeftValue =
ReactDOM.findDOMNode(buttonSearchRef.current).offsetLeft;
console.log(buttonSearchRefOffsetLeftValue); //got the value
})
return (
<div ref={buttonSearchRef}>He<div>
<Search buttonSearchRefOffsetLeftValue=
{buttonSearchRefOffsetLeftValue} />
)
}
const Search = (props) => {
console.log(props.buttonSearchRefOffsetLeftValue)//got undefined WHY?
}
The reason is when you declare it first like this, its value will be undefined by default
Then, it will pass this value first to
Searchcomponent before theuseEffectofHeaderis run. Thats why you getundefined. AFter that, when the DOM is fully rendered, the ref is attached, useEffect runs and updatebuttonSearchRefOffsetLeftValue, but this is not a React state or props. Therefore, it not updateprops.buttonSearchRefOffsetLeftValueinSearch, resulting it still keeps undefined.A quick fix for this is to put
buttonSearchRefOffsetLeftValuein a statenow your
Searchcomponent should log the console twice, with the second time printing out the value.