Kevin
Kevin

Reputation: 497

React Hooks Refs

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!

Upvotes: 20

Views: 29724

Answers (4)

Vignesh
Vignesh

Reputation: 204

By referring the input from the user in function hooks use useref().

function Canvas(){
  const firstNameRef=useref(null);
  const [firstName, setFirstName]=useState(); 
  const submitevent =()=>{
     e.preventDefault();
     setFirstName(firstNameRef.current.value);
  }
  return(
      <form>
        <input value={firstName} ref={firstNameRef}/>
        <button onClick={submitevent}>submit</button>
      </form>
  )
}

It will helps you for the ref hooks:)

Upvotes: 0

Sanderson Soares
Sanderson Soares

Reputation: 21

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>
    );
}

Upvotes: 2

Ilyas Assainov
Ilyas Assainov

Reputation: 2070

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>
    );
};

Upvotes: 12

carlosrberto
carlosrberto

Reputation: 893

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

Upvotes: 54

Related Questions