Search code examples
javascriptreactjssvgdynamicwidth

clientWidth function in React


I am experienced in working with Javascript, but am pretty new to working with React. When coding purely in javascript that would be rendered in browser, I would often use:

width = document.getElementById('element_id').clientWidth

to dynamically size my svg elements to different container sizes. Does something like this exist in React? I have been trying to use the same technique, but as expected, it does not work because the the template is rendered after the script is run.


Solution

  • Use can use this it work. useEffect(didUpdate);. Accepts a function that contains imperative, possibly effectful code.

    const App = () => {
        useEffect(() => {
            const width = document.getElementById('width').clientWidth;
            console.log({ width });
        }, []);
        
       return(
                <div id="width" />
       );
    }