anthino12
anthino12

Reputation: 958

React forwardRef for function component

I have this interface:

export interface INTERFACE1{
  name?: string;
  label?: string;
}

and then this function component:

export function FUNCTION1({
  name,
  label
}: INTERFACE1) {
  return (
    <CustomComponent name={name} label={label} />
  );
}

my goal is to access this CustomComponent from another component. I tried adding ref: React.createRef<any> inside the interface but it didn't click in. From my research, it seems that I need to use forwardRef but most of the online examples don't seem to work. Any ideas how can I reference my CustomComponent from outside, from different component, like this?

import React, { useCallback, useEffect, useState, createRef } from 'react';
import { FUNCTION1 } from 'FUNCTION1';

interface INTERFACE2 {
  loading: boolean;
}

export default function FUNCTION2({
  loading
}: INTERFACE2) {
  const areaRef = createRef<HTMLTextAreaElement>();

  return (
    <>
          <FUNCTION1
            name="NAME"
            label="LABEL"
            ref={areaRef}
          />
    </>
  );
}

areaRef throws an error that I should use forwardRef.

Upvotes: 0

Views: 2948

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53874

You don't really need a forwardRef here, please refer to: Why, exactly, do we need React.forwardRef?.

In your specific example:

  • Don't UPPER CASE your component name, its should only start with Capital
  • Pass your ref through any prop, see explanation in link above.
  • Use a hook useRef in function components, createRef is for classes.
function Foo2() {
  const areaRef = useRef();

  // Check ref
  useEffect(() => {
    console.log(areaRef.current);
  }, []);

  return <CustomComponent inneRef={areaRef} />;
}

function CustomComponent({ innerRef }) {
  return <textArea ref={innerRef} />;
}

Upvotes: 3

Related Questions