React – forwardRef() – Example

React

A component doesn’t expose its DOM nodes by default. You can opt into exposing a DOM node by using forwardRef and passing the second ref argument down to a specific node.

By default, each component’s DOM nodes are private. However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into forwardRef().

forwardRef() returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by forwardRef is also able to receive a ref prop.

Example

import { forwardRef, useRef } from 'react';

export default function ForwardRefDemo() {

    const selectControl = useRef(null);
    const Select = forwardRef(({ onChange, onBlur, name }, ref) => (
        <>
            <select name={name} ref={ref} onChange={onChange} onBlur={onBlur}>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30</option>
            </select>
        </>
    ));

    return (
        <form onSubmit={(e) => {
            e.preventDefault();
            console.log(selectControl.current)
            console.log(selectControl.current.value)
        }}>
            <label>Name: </label>
            <input name="name" label="Name" required /><br />
            <label>Age: </label>
            <Select name="age" label="Age" ref={selectControl} /><br />
            <input type="submit" /><br />
        </form>
    );
}
https://www.mldgroup.com

Vyštudovaný top manažér pôsobiaci najmä ako manažér, marketér, softvérový inžinier, konzultant, bloger, YouTuber a zatiaľ neúspešný hudobník a producent. V rámci praxe pôsobil v rôznych odvetviach na rôznych pozíciách v malých aj veľkých firmách, vrátane spoluprác a partnerstiev s významnými firmami či poradenskými spoločnosťami.

Pridaj komentár

Vaša e-mailová adresa nebude zverejnená. Vyžadované polia sú označené *