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.

3
  • 1
    What does it mean "access from another component", sounds like the XY problem. 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. Commented Aug 25, 2021 at 9:10
  • I edited my question, I added an example how is my intention to access the component through ref from another component. @DennisVash Commented Aug 25, 2021 at 9: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. Commented Aug 25, 2021 at 9:29

1 Answer 1

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} />;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.