Skip to content

Instantly share code, notes, and snippets.

@yyynnn
Last active June 27, 2020 12:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyynnn/6629e718393be4bb94a67aadf1e6c606 to your computer and use it in GitHub Desktop.
Save yyynnn/6629e718393be4bb94a67aadf1e6c606 to your computer and use it in GitHub Desktop.
import { compose, withHandlers } from 'recompose'
import { animateScroll } from 'react-scroll'
const scrollToFirstError = errors => {
const errorFields = errors
// Using breakable for loop
for (let i = 0; i < errorFields.length; i++) {
const fieldName = `position-${errorFields[i]}`
// Checking if the marker exists in DOM
const elements = document.querySelectorAll(`[name="${fieldName}"]`)
if (elements.length) {
animateScroll.scrollTo(elements[0].offsetTop - 50) // animate directly to the right position
break
}
}
}
const removeEmpty = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key])
else if (!obj[key]) delete obj[key]
})
return obj
}
const objToArray = obj => {
return Object.keys(obj)
}
export const withScrollToError = compose(
withHandlers({
handleScrollAndSubmit: ({ handleSubmit, form }) => e => {
const fieldsWithErrors = objToArray(removeEmpty(form.getState().errors)) // get this from render props of RFF <Form /> component
handleSubmit(e)
scrollToFirstError(fieldsWithErrors)
}
})
)
//then wrap your form from redred props with this HOC and pass handleScrollAndSubmit to <form/>'s onSubmit prop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment