Formik: Use React.forwardRef in <Formik>

Created on 14 Jan 2020  Â·  11Comments  Â·  Source: formium/formik

As of 2.1.2, <Formik> now allows for an innerRef prop. However, we should instead use React.forwardRef + React.useImperativeHandle. This is more intuitive and closer to best practices. The problem though, is that <Formik> takes TypeScript generics for Values and I'm not sure how to express this in with forwardRef. AFAICT, you can't because forwardRef returns a constant and constants can't have generics.

Help?!?!

Formik TypeScript help wanted

All 11 comments

How about:

export const Formik = React.forwardRef(function Formik<
  Values extends FormikValues = FormikValues,
  ExtraProps = {}
>(props: FormikConfig<Values> & ExtraProps, ref: any) {
  const formikbag = useFormik<Values>(props);
  const { component, children, render, innerRef } = props;

  // This allows folks to pass a ref to <Formik />
  React.useImperativeHandle(innerRef, () => formikbag);
  React.useImperativeHandle(ref, () => formikbag);
  ...

This seems to infer okay, but I might be misunderstanding.

Submit a PR?

Done!

Ah, never mind, I see the issue.

Doing a little cheating makes this possible. I didn't test too thoroughly, but it seems to work. The main issue is that I had to override the type inference (with as) and so this particular assignment will now be vulnerable to incorrect typings in the future.

https://github.com/jaredpalmer/formik/pull/2222

Some external issues related to forwardRef woes:
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/35834
https://stackoverflow.com/a/51898192

And finally, the rabbit hole, where someone attempts to define a way to let TS infer an open generic, and the TS team says "maybe one day": https://github.com/microsoft/TypeScript/pull/24626

I couldn’t find anything that worked before that doesn’t now. I guess the main concern is: going forward, how can you break it going forward in a way that the “as [...component...]” cast won’t complain about, and is that likely to happen?

Basically, a Formik contributor could change the types incorrectly. I wish we could ignore a specific rule so we wouldn't have to use as and we could protect against all the other errors, but for now as is the best protection we can get. as won't protect against most things, but it'll at least make sure it's kind of the same signature. I made a similar comment here: https://github.com/microsoft/TypeScript/pull/30215

Any updates on this issue? It's preventing my team from upgrading to Formik 2.x

+1

Was this page helpful?
0 / 5 - 0 ratings

Related issues

najisawas picture najisawas  Â·  3Comments

dearcodes picture dearcodes  Â·  3Comments

green-pickle picture green-pickle  Â·  3Comments

pmonty picture pmonty  Â·  3Comments

jaredpalmer picture jaredpalmer  Â·  3Comments