← All Articles A Product of Kinsa Creative

Manipulate the DOM from React using useRef

useRef is a React hook which is commonly used for manipulating the DOM.

import { useRef } from 'react';

function MyComponent({}) {
    // use useEffect() to know when the referenced DOM element has been rendered and, if so, call the DOM manipulation function
    useEffect(() => {
        if (myRef.current) {
            myDOMFunction();
        }
    }, []);

    // the DOM manipulation function
    function myDOMFunction() {
        // scroll object to center it on the page on the X-axis
        const myRef = myRef.current;
        myRef.scrollLeft = (myRef.scrollWidth - myRef.clientWidth) / 2;
    }

    return (
        
...
) }

Feedback?

Email us at enquiries@kinsa.cc.