S6759 false negative - functions written as const

  • What language is this for?
    TypeScript
  • Which rule?
    S6759. sonarjs/sonar-prefer-read-only-props
  • Why do you believe it’s a false-positive/false-negative?
    Because functions are functions.
  • Are you using
    “eslint-plugin-sonarjs”: “2.0.4”,
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

The following component doesn’t trigger the rule.

interface ReactProps {
  viewOnly: boolean;
}

const TextField = ({ viewOnly }: ReactProps) => {
// Component body
}

It seems only functions written with the function keyword are recognised by the rule. I am aware of no reasons for using function ComponentName() {} over const ComponentName = () => {} syntax.

1 Like

Yeah, it seems Sonar guys are struggling with the concept of React Component: there are a lot of FP or FN with React-related rules, which makes me think that they don’t understand React.

Anyway, even…

function TextField({ viewOnly }: ReactProps) {
// Component body
}

…should not trigger: this is not a React component. Would if be a React component, then the Number, String, Object…functions would also be React components.

A function becomes a React component as soon as it is rendered by one of the various render functions provided by React - hence rendered by another functional component or by one of the render functions exposed by React, or preact, or any other related library.

Hence, TextField should raise only when used at one point like here:

function TextField({ viewOnly }: ReactProps) {
// Component body
}

function Form() {
  return <TextField viewOnly={true}/>;
}

Also, this one should raise, but doesn’t:

function textField({ viewOnly }: ReactProps) {
// Component body
}

const TextField = textField;

function Form() {
  return <TextField viewOnly={true}/>;
}

Considering a function beginning with a capital letter as a component is so wrong that I really hope it is an oversight from the Sonar engineers instead of a thoughtful decision.

1 Like

Hi Stian,

thanks for feedback, I created ticket to improve the rule Jira