Kayote
Kayote

Reputation: 15637

How to Add Method to React Functional Component

I have a component with code as such:

const Abc: React.FC<AbcTypes> = ({...}) => {...}

Abc.getLayout = () => {...}

I am unclear how to define/ extend the method getLayout on Abc component in Typescript?

Upvotes: 0

Views: 2128

Answers (1)

thedude
thedude

Reputation: 9812

If you are asking how to type this, then you could do this:

const Abc: React.FC<AbcTypes> & { getLayout: () => SomeType } = ({...}) => {...}

Abc.getLayout = () => {...}

If you are asking for a way to define imperative API for your components then useImperativeHandle is what you are looking for.

This will allow the parent component to attach a ref to Abc and call the methods you define.

Here is an example on how to use it:

type AbcRef = {
  getLayout: () => string[]
}
const Abc = forwardRef<AbcRef>((props, ref) => {
  useImperativeHandle(ref, () => ({
    getLayout: () => ['abc'],
  }))

  return <div>Abc</div>
})

const Parent: FC = () => {
  const abcRef = useRef<AbcRef>(null)

  useEffect(() => {
    console.log(abcRef.current?.getLayout())
  }, [])

  return <Abc ref={abcRef} />
}

Upvotes: 6

Related Questions