reactjsref

Can I find an element inside a ref object in react?


I tried to getElementByClassName using ref but the error is getElementByClassName is not a function, I cannot use ref to the specified element. Can someone help ?

const ref = useRef(null);
//...
const handleAction = () => {
    if(ref.current) {
        console.log('I get here')
        const elem = ref.current.getElementByClassName('myClass')
    }
}

return (<div>
     <component ref={ref} />
     <button onClick={handleAction} />
</div>)

I got to the console.log('i get here')


Solution

  • Change the statement to

    const elem = ref.current.getElementsByClassName('myClass')
    

    The function name includes elements (plural) and not element.
    Also, it returns an array of all the matching elements.