0

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.

anthino12
  • 770
  • 1
  • 6
  • 29
  • 1
    What does it mean "access from another component", sounds like [the XY problem](https://xyproblem.info/). Please show a full example of what you trying to achieve, an example of you trying to "access" your component, and use it will be helpul. – Dennis Vash Aug 25 '21 at 09:10
  • I edited my question, I added an example how is my intention to access the component through ref from another component. @DennisVash – anthino12 Aug 25 '21 at 09:17
  • 1
    Your example isn't clear enough. And what exactly are you trying to achieve. Trying to use ref might not be the appropriate way of doing that. – Joshua Aug 25 '21 at 09:29

1 Answers1

3

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} />;
}
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118