1

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>
    )
  })
1
  • Use useRef hook in App to create (and use i.e. access that was already created) the ref. Why is it null? It depends on your code. It might also be undefined because you gave it no initial value in createRef<FormHandles>(); so, from where should it get the value? Commented May 28, 2021 at 13:48

2 Answers 2

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

Comments

3

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);

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.