Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hooks Refs

Tags:

So I decidet to rewrite my React Class Component into React Hook Component, And in my Class Component I did

<canvas ref='canvas'></canvas>

This approach didn't work anymore. How should I use refs then? In documentation only said that refs are still work.

Thank you!

like image 950
Kevin Avatar asked Dec 08 '18 00:12

Kevin


People also ask

What is REF IN React hooks?

Refs provide a way to access DOM nodes or React elements created in the render method. In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props.

How do you use refs with hooks?

In order to work with refs in React you need to first initialize a ref which is what the useRef hook is for. This hook is very straightforward, and takes an initial value as the only argument. This hook then returns a ref for you to work with.

What is useRef () in React?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

What are React refs?

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.


2 Answers

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

like image 104
carlosrberto Avatar answered Sep 21 '22 23:09

carlosrberto


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>
    );
};
like image 45
Ilyas Assainov Avatar answered Sep 21 '22 23:09

Ilyas Assainov