In my React/TypeScript app that uses Formik, I am getting the error
Object is possibly 'null'. TS2531
125 | <Modal.Footer>
> 126 | <Button variant="primary" type="submit" form="nicknameForm" disabled={!(formRef.current.isValid && formRef.current.dirty)}>Apply</Button>
| ^
127 | </Modal.Footer>
128 | </Modal>
129 | )
Tried changing formRef.current.isValid
to formRef!.current.isValid
and formRef.current.dirty
to formRef!.current.dirty
but the error persists.
Why is this so, and how can we fix this error? Thank you!
import React, { useState, useEffect, useRef } from 'react';
import { Button, Modal, Form } from 'react-bootstrap';
import { Formik } from 'formik';
interface IModal {
show: boolean;
handleClose: () => void;
}
export function NicknameModal({show, handleClose}: IModal) {
const formRef = useRef(null);
return (
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>My Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<Formik
initialValues={{
nickname: '',
}}
innerRef={formRef}
onSubmit={(
values,
{ setSubmitting }
) => {
setSubmitting(true);
handleClose();
setSubmitting(false);
}}
>
{({values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, setFieldValue }) => (
<Form id="nicknameForm" onSubmit={handleSubmit}>
<Form.Group controlId="formNickname">
<Form.Label>Nickname</Form.Label>
<Form.Control type="text" name="nickname" onChange={handleChange} onBlur={handleBlur} value={values.nickname} />
</Form.Group>
</Form>
)}
</Formik>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" type="submit"
disabled={!(formRef.current.isValid && formRef.current.dirty)}
form="nicknameForm">Apply</Button>
</Modal.Footer>
</Modal>
)
}
UPDATE:
If const formRef = useRef(null);
is changed to const formRef = useRef();
, we now encounter a different error:
Type 'MutableRefObject<undefined>' is not assignable to type '((instance: FormikProps<{ nickname: string; }> | null) => void) & MutableRefObject<undefined>'.
Type 'MutableRefObject<undefined>' is not assignable to type '(instance: FormikProps<{ nickname: string; }> | null) => void'.
Type 'MutableRefObject<undefined>' provides no match for the signature '(instance: FormikProps<{ nickname: string; }> | null): void'. TS2322
71 | nickName: '',
72 | }}
> 73 | innerRef={formRef}
| ^
74 | onSubmit={(
75 | values: Values,
76 | { setSubmitting }: FormikHelpers<Values>
useRef
but I have to look up what the appropriate type would be for theinnerRef
of aFormik
. – ThreecolorFormik
even have aninnerRef
prop?Field
does: formik.org/docs/api/field#innerref but I am not seeing it documented onFormik
formik.org/docs/api/formik – Threecolor