Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HTML elements inside a React component

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?

like image 501
Yaron Avatar asked Dec 20 '25 02:12

Yaron


2 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

like image 137
Vencovsky Avatar answered Dec 21 '25 21:12

Vencovsky


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.

like image 34
Sirwan Afifi Avatar answered Dec 21 '25 20:12

Sirwan Afifi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!