0

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?

1
  • Bad idea. Please use useState or useEffect instead Commented Nov 23, 2020 at 15:11

1 Answer 1

6

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

5 Comments

Thank you, that did it.
Hey @thedude, quick question. Is attaching a function to a react functional component better or using useImperativeHandle? For us, just attaching a function is doing the trick, but people are asking us to not do it. So useImperativeHook seems like our only option. Wondering what are the pros and cons of both.
@DhavalJardosh not sure I understand, perhaps create a new question here with more details
Used to look so much cleaner with classes.. I guess it's just the way the progress goes.. Getting rid of OOP and ending up with huge load of nonsense boilerplate code everywhere..

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.