Reputation: 958
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
Reputation: 53874
You don't really need a forwardRef
here, please refer to: Why, exactly, do we need React.forwardRef?.
In your specific example:
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