0

I'm trying to get the width of an element, and to do this I'm using the following...

export default () => {
    const { sidebarOpen } = useContext(AuthContext)
    const containerRef = useRef()

    const getWidth = () => myRef.current.getBoundingClientRect().width

    const [width, setWidth] = useState(0)

    console.log(sidebarOpen)

    useEffect(() => {
        const handleResize = () => setWidth(getWidth())

        if(myRef.current) setWidth(getWidth())

        window.addEventListener("resize", handleResize)
        console.log('abc', myRef.current.offsetWidth)

        return () => window.removeEventListener("resize", handleResize)
    }, [myRef, sidebarOpen])

    console.log(width)

    return (
        <div ref={containerRef}>
            ...
        </div>
    )
}

When the width of the screen is changed in dev tools page resize, it works fine, but when the value of sidebar changes from 'true' to 'false' (or vice-versa). It returns the previous value of the container width. Does anyone know what I'm doing wrong, I need to get the most up to date value of the container width every time it changes, whether this is caused by a change to 'sidebarOpen' or not.

1
  • You are currently measuring the width of the window not of the element (the div). You should do containerRef.current.addEventListener Commented May 9, 2022 at 11:47

1 Answer 1

1

By default, a div element takes the full width of its parent.

I guess you're using flexbox for the sidebar, so when it closes, the element that contains the content (not the sidebar) expands to the full width of the available space.

This might be the issue that you're facing.

The div with flexbox (on the left we have the Sidebar component and on the right the content):

Div with sidebar

And right now, when there is no Sidebar:

No sidebar

As another example, let's create a div that has no other property rather than backgroundColor:

Eg:

<div style={{backgroundColor: 'red'}}>Hello</div>

And the result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.