Skip to content

[Bug]: Should jsx-no-leaked-render cover unintended return values as well? #3618

Open

Description

Is there an existing issue for this?

  • I have searched the existing issues and my issue is unique
  • My issue appears in the command-line and not only in the text editor

Description Overview

Conditionally rendering a string value with extra braces are hard to spot and can cause a runtime error.

Should jsx-no-leaked-render cover also return values?

type Props = {
  isInteractive: boolean
  label: string
}
const Test: React.FunctionComponent<Props> = ({ isInteractive, label }) => (
  <div>
    {/* Will render `{label}` (object) instead of a string when `isInteractive` is false */}
    { isInteractive
      ? <button>{label}</button>
      : {label}
    }
    
    { isInteractive && <button>{label}</button> }
    {/* ...same issue as above */}
    { !isInteractive && {label} }
  </div>
)

When isInteractive is false the code will return an object instead of a string, but it's easy to miss in the ternary case. The error is Uncaught Error: Objects are not valid as a React child (found: object with keys {label}). If you meant to render a collection of children, use an array instead.

Appears both in VS Code Eslint plugin (dbaeumer.vscode-eslint) and command line running npx eslint . with following config:

{
  ...
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended-type-checked",
    "plugin:react/recommended",
    "plugin:react-hooks/recommended"
  ],
  ...
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    }
  },
  ...
  "plugins": ["react", "@typescript-eslint"],
  "rules": {
    "react/jsx-no-leaked-render": "error"
  },
  "settings": {
    "react": {
      "version": "detect"
    }
  }
}

Expected Behavior

Report extraneous braces around strings on conditional renders. Remove extra braces on fix.

const Test: React.FunctionComponent<Props> = ({ isInteractive, label }) => (
  <div>
    { isInteractive
      ? <button>{label}</button>
      : label
    }
    
    { isInteractive && <button>{label}</button> }
    { !isInteractive && label }
  </div>
)

eslint-plugin-react version

v7.33.2

eslint version

v8.47.0

node version

v20.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions