'How to use TypeScript and forwardRef in ReactJS?
I'm having a problem when using forwardRef
with TypeScript.
What I want? pass a typed ref to the child component.
What am I getting
value of console.log - child component null
Code for parent component
// component parent
import { FormHandles } from '@unform/core';
export const App = () => {
const formRef = createRef<FormHandles>();
return (
<Child ref={formRef} />
)
}
Code for child component
// component child
import { FormHandles } from '@unform/core';
export const Child = forwardRef<FormHandles>((props, ref) => {
console.log('child component', ref.current);
return (
<div>any thing</div>
)
})
Solution 1:[1]
This is an example to show you how to use forwardRef with typescript
import React, { ChangeEventHandler } from 'react';
import Button from '../button';
import TextInput from '../text-input';
import SearchIcon from '../../icons/Search';
export interface SearchProps {
className?: string;
size?: ComponentSize;
width?: string;
value?: string;
onChange?: ChangeEventHandler<HTMLInputElement>;
placeholder?: string;
}
const Search: React.ForwardRefRenderFunction<HTMLDivElement, SearchProps> = (props, ref) => {
const {
size = 'default',
className,
value,
onChange,
placeholder,
width = '100%',
} = props;
return (
<div
ref={ref}
className={className}
width={width}
>
<TextInput
value={value}
onChange={onChange}
placeholder={placeholder}
clearable
/>
<Button type='secondary' icon={SearchIcon} />
</div>
);
}
export default React.forwardRef<HTMLDivElement, SearchProps>(Search);
Solution 2:[2]
import React, {createRef, forwardRef} from 'react';
type Props = { children: React.ReactNode; type: "submit" | "button" };
type Ref = HTMLButtonElement;
const Child = React.forwardRef<Ref, Props>((props, ref) => {
console.log(ref);
return (<button ref={ref} className="MyChild" type={props.type}>{props.children}</button>);
});
function App() {
const ref = React.createRef<HTMLButtonElement>();
return (
<Child type="button" ref={ref}>Click Me</Child>
)
}
export default App;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel |
Solution 2 | Pramod Kumar |