Accessing HTML elements inside a React component

Viewed 553

I have a React component InputComponent which I cannot edit, and I would like to get a reference to one of its inner divs. (for example for the purpose of focusing on the input field).

const RefsExamplePage = () => {

    return (
        <div>

            <div>
                <InputComponent
                title="Test component"
                ></InputComponent>
            </div>

        </div>

    )
}

export default RefsExamplePage;

How do I achieve this?

3 Answers

which I cannot edit

If you can't edit it, the only thing you can do is pass ref to it and hope the InputComponent have refs implemented.

e.g.

const RefsExamplePage = () => {

    // use inputRef.current to access the input reference
    const inputRef = React.useRef()    

    return (
        <div>

            <div>
                <InputComponent
                    ref={inputRef}
                    title="Test component"
                />
            </div>

        </div>

    )
}

If this doesn't work or give you some error, you will need to modify the InputComponent

If InputComponent doesn't provide ref you can wrap its parent (the div container) then set ref for it:

import React, { useRef } from "react";

const RefsExamplePage = () => {
    const container = useRef();
    return (
        <div>

            <div ref={container}>
                <InputComponent
                title="Test component"
                ></InputComponent>
            </div>

        </div>

    )
}

export default RefsExamplePage;

Then you can access the child element through the div's ref.

Use useRef() to create a ref to the component itself. This way you can get the components reference and you can use .current property of it to get the underlying DOM:

const RefsExamplePage = () => {

    const inputRef = useRef();

    const getInput = e => {
       // here get the any dom node available
       inputRef.current.querySelector('input').focus();
    };

    return (....
           <InputComponent 
             ref={inputRef} 
             onClick={getInput} 
             title="Test component"/> // <---if no child are passed change to self closing
        ....)
}
Related