react create ref in typescript

To create a ref in TypeScript, we can use the createRef function from the React library. The createRef function returns a ref object that can be attached to React components.

Here's an example of how to create a ref in TypeScript:

import React, { useRef } from 'react';

interface MyComponentProps {
  // define component props here
}

const MyComponent: React.FC<MyComponentProps> = ({ /* destructured props */ }) => {
  const myRef = useRef<HTMLInputElement>(null);

  const handleClick = () => {
    if (myRef && myRef.current) {
      myRef.current.focus();
    }
  };

  return (
    <div>
        <input type="text" ref={myRef} />
        <button onClick={handleClick}>Focus input</button>
    </div>
  );
};
484 chars
23 lines

In this example, we create a ref using useRef and specify the type of the ref as HTMLInputElement. With the ref created, we then attach it to an input element using the ref attribute. Finally, we create a button that, when clicked, calls a function that uses the ref to focus the input element.

By using types in our ref definition, TypeScript will ensure that only compatible DOM elements can be attached to the ref, which helps to prevent runtime errors.

gistlibby LogSnag