Should I use React-hook-form or write my own input and validation code? What is preferred in the industry and what do you suggest?

Formik and react-final-form are pretty popular solutions. They both have the same API for validation - you define a function either at Form or Field level which receives values/value and may return an error.

How you do the actual validation is hence up to you. It can be some 3rd party lib (Yup), or you define the rules yourself and use something like this to piece it together.

import get from 'lodash/get'
import set from 'lodash/set'
type Rule<T = any> = (value: T, data: { [key: string]: T }) => string | undefined
const joinRules = <T = any>(rules: Rule<T>[]) => (value: T, data: { [key: string]: T }) =>
rules
// Test value against all rules
.map(rule => rule(value, data))
// Filter null errors & pick the first one
.filter(error => Boolean(error))[0]
export function validator(rules: { [key: string]: Rule | Rule[] }) {
return (data = {}) => {
let errors = {}
Object.keys(rules).forEach(key => {
// concat enables both functions and arrays of functions
const rule = joinRules(([] as Rule[]).concat(rules[key]))
const error = rule(get(data, key), data)
if (error) {
errors = set(errors, key, error)
}
})
return errors
}
}
const required = (value?: string) => {
if (!value) {
return 'Required'
}
}
function minLength(limit: number) {
return (value: string) => {
if (value && value.length < limit) {
return `Min ${limit} characters`
}
return undefined
}
}
<Form validate={validator({ name: required, description: \[required, minLength(10)\], })} />

/r/reactjs Thread