const ref = React.createRef();
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
setWidth((ref as any).current?.clientWidth);
console.log(width);
});
<Dropdown
setDropdownVisible={setDropdownVisible}
title={<DropdownTitle />}
ref={ref}
className={`user-info flex max-w-full justify-center whitespace-nowrap border pr-1 sm:py-0 ${ dropdownVisible ? ' min-w-[180px] rounded-t-[25px] p-2 sm:p-0' : 'rounded-full'}`}isPortal={true}>
I am tyring to access the width of an element , i have used portal. it either shows with as 0 or undefined. how do i get the width of the element
CodePudding user response:
Dropdown is a react component so you should use forwardRef and assign the ref to the element inside the Dropdown component.
const Dropdown = React.forwardRef((props, ref) => <div ref={ref}>Dropdown</div>);
Or I think if you wrapped the Dropdown in a div for example and used the ref with this div, It should work
<div ref={ref}>
<Dropdown title={<>sdfds</>} />
</div>
CodePudding user response:
Your Dropdown is not a DOM element, you should put ref={ref} in a Dom element such as or . In your sitiation, You can use forwardRef if is coded by yourself.