Created
November 1, 2018 23:41
-
-
Save dphrag/4db3b453e02567a0bb52592679554a5b to your computer and use it in GitHub Desktop.
Formik Scroll To First Invalid Element W/O Refs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { connect } from 'formik'; | |
class ErrorFocus extends React.Component { | |
componentDidUpdate(prevProps) { | |
const { isSubmitting, isValidating, errors } = prevProps.formik; | |
const keys = Object.keys(errors); | |
if (keys.length > 0 && isSubmitting && !isValidating) { | |
const selector = `[id="${keys[0]}"]`; | |
const errorElement = document.querySelector(selector); | |
errorElement.focus(); | |
} | |
} | |
render() { | |
return null; | |
} | |
} | |
export default connect(ErrorFocus); |
I used this for ReactSelect :
import React, { useEffect } from 'react';
import { useFormikContext } from 'formik';
const ScrollToFieldError = ({ scrollBehavior = { behavior: 'smooth', block: 'center' } }) => {
const { submitCount, isValid, errors } = useFormikContext();
useEffect(() => {
if (isValid) return;
const fieldErrorNames = getFieldErrorNames(errors);
let element;
if (fieldErrorNames[0].includes('.type')) {
element = document.querySelector(`input[aria-label='${fieldErrorNames[0]}']`);
} else {
element = document.querySelector(`input[name='${fieldErrorNames[0]}']`);
}
if (!element) return;
// Scroll to first known error into view
element.scrollIntoView(scrollBehavior as any);
// Formik doesn't (yet) provide a callback for a client-failed submission,
// thus why this is implemented through a hook that listens to changes on
// the submit count.
}, [submitCount]);
return null;
};
Put ScrollToFieldError within formiks Form.
Pass aria-label props in ReactSelect .
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
anybody able to fix for react-select?