ESLint plugin for react-hook-form

Overview

eslint-plugin-react-hook-form

npm version GitHub

react-hook-form is an awsome library which provide a neat solution for building forms. However, there are many rules for the API which may be missed by the developer. This plugin aims to check those rules automatically thourgh ESLint. Thus brings better DX for react-hook-form.

Installation

You'll first need to install ESLint:

$ npm i eslint --save-dev

Next, install eslint-plugin-react-hook-form:

$ npm install eslint-plugin-react-hook-form --save-dev

Usage

Add react-hook-form to the plugins section of your .eslintrc configuration file. You can omit the eslint-plugin- prefix:

{
  "plugins": ["react-hook-form"]
}

Then configure the rules you want to use under the rules section.

{
  "rules": {
    "react-hook-form/destructuring-formState": "error"
  }
}

or start with the recommended rule set:

{
  "extends": "plugin:react-hook-form/recommended"
}

Supported Rules

Rule Description Recommended Fixable
destructuring-formState Use destructuring assignment to access the properties of formState. ⛔️
no-access-control Avoid accessing the properties of control ⛔️
no-nested-object-setvalue Avoid nested object in second argument of setValue ⛔️ 🔧

Key

Icon Description
⛔️ Reports as error in recommended configuration
⚠️ Reports as warning in recommended configuration
🔧 Rule is fixable with eslint --fix

License

MIT

Comments
  • The plugin crashes unexpectedly when not destructuring the result of calling useForm

    The plugin crashes unexpectedly when not destructuring the result of calling useForm

    Describe the bug The plugin crashes unexpectedly when not destructuring the result of calling useForm.

    To Reproduce

    1. The code you are going to lint.
    const { useForm } = require('react-hook-form')
    export function Component() {
      const formMethods = useForm()
      return null
    }
    
    1. Your ESlint config
    {
      ...
      'react-hook-form/no-nested-object-setvalue': ['error', { bracketAsArrayIndex: true }],
    }
    

    Expected behavior I expect the React Hook Form Eslint plugin to not crash.

    Actual behavior The React Hook Form ESLing plugin crashes with the following error message:

    TypeError: Cannot read property 'find' of undefined
    Occurred while linting my-project/components/TestComponent.jsx:3
        at check (my-project/node_modules/eslint-plugin-react-hook-form/lib/rules/no-nested-object-setvalue.js:48:53)
        at my-project/node_modules/eslint/lib/linter/safe-emitter.js:45:58
        at Array.forEach (<anonymous>)
        at Object.emit (my-project/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
        at NodeEventGenerator.applySelector (my-project/node_modules/eslint/lib/linter/node-event-generator.js:254:26)
        at NodeEventGenerator.applySelectors (my-project/node_modules/eslint/lib/linter/node-event-generator.js:283:22)
        at NodeEventGenerator.enterNode (my-project/node_modules/eslint/lib/linter/node-event-generator.js:297:14)
        at CodePathAnalyzer.enterNode (my-project/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:711:23)
        at my-project/node_modules/eslint/lib/linter/linter.js:952:32
        at Array.forEach (<anonymous>)
    

    Enviornment (please complete the following information):

    • Eslint version: 7.12.1
    • Node version: v14.18.3
    • React-Hook-Form version: 6.15.8
    • eslint-plugin-react-hook-form version: 0.2.2

    Additional context n/a

    opened by akd-io 6
  • The plugin crashes unexpectedly when using `...rest` syntax in the destructuring of the result of calling useForm

    The plugin crashes unexpectedly when using `...rest` syntax in the destructuring of the result of calling useForm

    Describe the bug The plugin crashes unexpectedly when using ...rest syntax in the destructuring of the result of calling useForm.

    To Reproduce

    1. The code you are going to lint.
    const { useForm } = require('react-hook-form')
    export function Component() {
      const { watch, ...restFormMethods } = useForm()
      return null
    }
    
    1. Your ESlint config
    {
      ...
      'react-hook-form/no-nested-object-setvalue': ['error', { bracketAsArrayIndex: true }],
    }
    

    Expected behavior I expect the React Hook Form Eslint plugin to not crash.

    Actual behavior The React Hook Form ESLing plugin crashes with the following error message:

    TypeError: Cannot read property 'name' of undefined
    Occurred while linting my-project/components/TestComponent.jsx:3
        at my-project/node_modules/eslint-plugin-react-hook-form/lib/rules/no-nested-object-setvalue.js:49:24
        at Array.find (<anonymous>)
        at check (my-project/node_modules/eslint-plugin-react-hook-form/lib/rules/no-nested-object-setvalue.js:48:53)
        at my-project/node_modules/eslint/lib/linter/safe-emitter.js:45:58
        at Array.forEach (<anonymous>)
        at Object.emit (my-project/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
        at NodeEventGenerator.applySelector (my-project/node_modules/eslint/lib/linter/node-event-generator.js:254:26)
        at NodeEventGenerator.applySelectors (my-project/node_modules/eslint/lib/linter/node-event-generator.js:283:22)
        at NodeEventGenerator.enterNode (my-project/node_modules/eslint/lib/linter/node-event-generator.js:297:14)
        at CodePathAnalyzer.enterNode (my-project/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:711:23)
    

    Enviornment (please complete the following information):

    • Eslint version: 7.12.1
    • Node version: v14.18.3
    • React-Hook-Form version: 6.15.8
    • eslint-plugin-react-hook-form version: 0.2.2

    Additional context n/a

    opened by akd-io 3
  • fix: Fix typos

    fix: Fix typos

    Hi, thanks for this library. It would have saved me some trouble if I knew about it yesterday. I noticed some typos in the error message, so this PR cleans them up. I don't think useDestuctor is user-facing, but I fixed that anyway.

    image

    opened by david-crespo 2
  • `no-nested-object-setvalue` throws when passing a function call

    `no-nested-object-setvalue` throws when passing a function call

    Describe the bug react-hook-form/no-nested-object-setvalue is thrown with message Avoid passing object or array as second argument in setValue since this is less performant, when using the following syntax:

    setValue("someName", myFunctionReturningANumber())
    

    To Reproduce

    1. The code you are going to lint.
    function Component() {
      const {useValue} = useForm();
    
      const myFunctionReturningANumber = () => 5
    
      setValue("someName", myFunctionReturningANumber())
    
      return null;
    }
    
    1. Your ESlint config
    {
      ...
      'react-hook-form/no-nested-object-setvalue': ['error', { bracketAsArrayIndex: true }],
    }
    

    Expected behavior Expect react-hook-form/no-nested-object-setvalue not to throw an error.

    Actual behavior react-hook-form/no-nested-object-setvalue throws with message Avoid passing object or array as second argument in setValue since this is less performant

    Enviornment (please complete the following information):

    • Eslint version: 7.12.1
    • Node version: v14.18.3
    • React-Hook-Form version: 6.15.8
    • eslint-plugin-react-hook-form version: 0.2.3

    Additional context n/a

    bug 
    opened by akd-io 2
  • TypeError: Cannot read property 'type' of null when using `for...of`

    TypeError: Cannot read property 'type' of null when using `for...of`

    Describe the bug ESLint exits with fatal error.

    To Reproduce

    1. The code you are going to lint.
    for (const element of array) {
      bar(element);
    }
    
    1. Your ESlint config
    {
      "parserOptions": {
        "ecmaVersion": "latest"
      },
    
      "plugins": ["react-hook-form"],
    
      "rules": {
        "react-hook-form/destructuring-formstate": "error"
      }
    }
    
    

    Expected behavior No fatal error.

    Actual behavior

    Oops! Something went wrong! :(
    
    ESLint: 8.6.0
    
    TypeError: Cannot read property 'type' of null
    Occurred while linting /example/example.js:1
    Rule: "react-hook-form/destructuring-formstate"
        at check (/example/node_modules/eslint-plugin-react-hook-form/lib/rules/destructuring-formstate.js:45:19)
        at ruleErrorHandler (/example/node_modules/eslint/lib/linter/linter.js:1079:28)
        at /example/node_modules/eslint/lib/linter/safe-emitter.js:45:58
        at Array.forEach (<anonymous>)
        at Object.emit (/example/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
        at NodeEventGenerator.applySelector (/example/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
        at NodeEventGenerator.applySelectors (/example/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
        at NodeEventGenerator.enterNode (/example/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
        at CodePathAnalyzer.enterNode (/example/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:795:23)
        at /example/node_modules/eslint/lib/linter/linter.js:1110:32
    

    Enviornment (please complete the following information):

    • Eslint version: 8.6.0
    • Node version: 14.18.2
    • React-Hook-Form version: 0.2.1

    Additional context

    bug 
    opened by EvgenyOrekhov 1
  • fix: handle different cases of the id of VariableDeclarator

    fix: handle different cases of the id of VariableDeclarator

    • VariableDeclarator.id may have different kinds of types. What we are interested in is the ObjectPattern. Add this condition to avoid errors in #13 and #14 . (Reference: https://github.com/estree/estree/blob/master/es2015.md#patterns)
    • Upgrade the ecma version to 9 to support RestElement (References: https://github.com/estree/estree/blob/master/es2018.md#patterns)

    fix: #13 #14

    bug 
    opened by andykao1213 0
  • fix: handle nullish `init` in `VariableDeclarator`

    fix: handle nullish `init` in `VariableDeclarator`

    VariableDeclarator.init will be null if this declarator isn't initialized. In particular, if the declarator hasn't been assigned by any value, the property init will be null. Thus, the pattern like const a will be failed. We fix the issue by using ES6 optional chaining.

    fix #11

    bug 
    opened by andykao1213 0
  • ci: use workflow to lint PR title

    ci: use workflow to lint PR title

    Since we are going to leverage the squash-based workflow, it's no longer needed to lint every commit. Instead, all we need to lint is the PR title, which is going to be the commit message of the squash-merged commit.

    opened by andykao1213 0
  • Feature: Strictly check `formState`

    Feature: Strictly check `formState`

    Add more conditions to the target variable formState:

    • Check if the initializer is useForm()
    • Check the alias. e.g. {formState: fs}
    • Support useFormState()
    opened by andykao1213 0
Releases(v0.2.5)
Owner
Chuan-Tse Kao
Software engineer enthusiastic in Web technologies.
Chuan-Tse Kao
An extremely helpful React Hook to trap the focusable elements / Hello Modals! Hello a11y!

react-use-focus-trap Everytime when people implement Modals... ...People forget that pro users as well as users that are permanently or temporarily re

David Lorenz 18 Nov 30, 2022
React hook library, ready to use, written in Typescript.

usehooks-ts React hook library, ready to use, written in Typescript. npm i usehooks-ts Created by Julien Caron and maintained with ❤️ by an amazing te

Julien 2.8k Jan 5, 2023
Small (0.5 Kb) react hook for getting media breakpoints state info in runtime

tiny-use-media Small (0.5 Kb) react hook for getting media breakpoints state info in runtime Usage npm i tiny-use-media --save Adn in your react code

Valeriy Komlev 51 Dec 13, 2022
A reusable react hook that preserves a components semantic accessibility to create a visual block link.

useAccessibleBlockLink is a reusable react hook that preserves a components semantic accessibility to create a visual block link. This hook supports multiple links within the same block.

Wayfair Tech – Incubator 4 Nov 28, 2022
📋 useClipboardApi() is a React Hook that consumes Web Clipboard API.

?? use-clipboard-api useClipboardApi() is a React Hook that consumes Web Clipboard API. Table of Contents Motivation Usage Contributing Bugs and Suges

Helder B. Berto 22 Dec 15, 2022
A custom react hook to use a dialogs easily.

dialog-hook The dialog-hook is a custom react hook to use a dialog easily. First of all it is necessary to install the package in your project some co

Levy Mateus Macedo 2 Mar 29, 2022
This hook allows you to isolate and manage the state within the component, reducing rendering operations and keeping the source code concise.

React Hook Component State This hook allows you to isolate and manage the state within the component, reducing rendering operations and keeping the so

Yongwoo Jung 2 May 15, 2022
A hook based project created during 20-Dec week ReactJS workshop

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Nabendu 1 Dec 25, 2021
🌐 Unlimited free google translate component & hook

React Native Translator Preview Introduce Free translate component & hook Never need api key, This library is Unlimited free Support translators Googl

Hyun 34 Dec 18, 2022
Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement.

useAsyncQuery Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement. Usage

Alasdair McLeay 7 Nov 16, 2022
Script to remove unnecessary properties from package.json on prepublish hook

clean-pkg-json Script to remove unnecessary properties from package.json on prepublish hook. Support this project by ⭐️ starring and sharing it. Follo

hiroki osame 37 Oct 16, 2022
An easy hook to use with expo-calendar library!

useCalendar Hook ?? Updated to Expo SDK45 This is an easy hook to use expo-calendar. It allows you: Get access permission to calendar Open settings to

AtilaDev 12 Nov 1, 2022
A custom ESLint rule to allow static deps in React Hooks ⚛️

eslint-plugin-react-hooks-static-deps A custom ESLint rule to allow static deps in React Hooks ⚛️ Motivation react-hooks/exhaustive-deps is a really n

Stoïk 3 Apr 5, 2022
A Higher Order Component using react-redux to keep form state in a Redux store

redux-form You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of Redux

Redux Form 12.6k Jan 3, 2023
🏁 High performance subscription-based form state management for React

You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of React Final Form.

Final Form 7.2k Jan 7, 2023
An easy-to-use super customisable form validation library for React.

An easy-to-use super customisable form validation library for React. This library handles all of your form states using built in useReducer hook of react.

Himanshu Bhardwaz 2 Jun 30, 2022
Form handler in React-MobX

MobX Light Form ✨ MobX Form State Management with automatic validation Seperate subjects which manage form data to prevent duplication of data and ens

정윤재 3 Nov 30, 2022
An example of a schema-based form system for React.

React Advanced Form An example of a schema-based form system in React. Define your schema, and pass it into the form. Supports basic conditional schem

Tania Rascia 111 Dec 31, 2022
🪱 Zorm - Type-safe
for React using Zod

React Zorm Type-safe <form> for React using Zod! Features / opinions ?? Type-safe Get form data as a typed object Typo-safe name and id attribute gene

Esa-Matti Suuronen 503 Dec 25, 2022