react-hook-form isDirty seems weird for me

Viewed 2932

Today, I started to use react-hook-form and the isDirty variable seems quite weird for me. It is always true although only the focus was given to any input elements.

I expect isDirty should be true only when value of input element changes. Is that normal in react-hook-form?

// I had to make workaround like this. but I am not sure if this is normal for everybody.
const closeForm = () => {
    const { dirtyFields } = form.formState
    const isReallyDirty = Object.keys(dirtyFields).length > 0

    if (isReallyDirty) {
        if (window.confirm("Discard the changes?")) {
            dispatch(closeItem())
        }
    } else {
        dispatch(closeItem())
    }
}

UPDATE: I think this is a bug of react-hook-form? react-hook-form version 6.11.0

This happens only when React.forwardRef was used.

const TextareaBox = ({ ref, ...props }) => {
    const { errors, name } = props
    const { required, ...restProps } = props

    return (
        <Row>
            <Label {...props} columnSize={2} />
            <Col lg={10}>
                <textarea id={name} {...restProps} maxLength="200" rows="3" ref={ref} />
                <ErrorMessage className="errorMessage" errors={errors} name={name} as="p" />
            </Col>
        </Row>
    )
}

const TextareaBox = React.forwardRef((props, ref) => {
    const { errors, name } = props
    const { required, ...restProps } = props

    return (
        <Row>
            <Label {...props} columnSize={2} />
            <Col lg={10}>
                <textarea id={name} {...restProps} maxLength="200" rows="3" ref={ref} />
                <ErrorMessage className="errorMessage" errors={errors} name={name} as="p" />
            </Col>
        </Row>
    )
})
1 Answers

I had a similar issue and I ended up solving it by checking length of dirtyFields property of the formState.

In react hook form, you may feel that isDirty behaves more like it is isTouched. But you have to pass the defaultValue to the input field because RHF needs a value to compare against as mentioned in the official documents.

enter image description here

Let me know if that makes sense.

Related