React Hooks Refs

Showing just one example of how it worked for me in a non-verbose way in React Native.

export function Screen() {

   /*
    * Call function for example of access to the component, 
    * being able to access calls to its functions.
    */
    const callRef = () => {
       testeRef.example();
    };

    return (
       <CustomComponent ref={(e) => testRef = e}></CustomComponent>
    );
}

In case you would like to use refs inside a map function:

export default () => {
    const items = ['apple', 'orange', 'mango'];

    // 1) create an array of refs
    const itemRefs = useRef(items.map(() => React.createRef()));

    useEffect(() => {
        // 3) access a ref, for example 0
        itemRefs.current[0].current.focus()
    }, []);

    return (
        <ul>
            {items.map((item, i) => (
                // 2) attach ref to each item
                <li key={item} ref={itemRefs.current[i]}>{item}</li>
            ))}
        </ul>
    );
};

With hooks you can use the useRef hook.

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}

look at the useRef docs here: https://reactjs.org/docs/hooks-reference.html#useref

Tags:

Reactjs