jsx-key

Try in Playground
jsx-react

oscar143

Best PracticeWarning

0

No tags

No CWE or CVE

Disallow missing key props in iterators/collection literals

Warn if an element that likely requires a key prop--namely, one present in an array literal or an arrow function expression.

When Not To Use It

If you are not using JSX then you can disable this rule.

Also, if you have some prevalent situation where you use arrow functions to return JSX that will not be held in an iterable, you may want to disable this rule.

Ast Rule: html element


jsx-key

How to write a rule
function visit(node) {
  const currentFunctionCall = node.context.currentFunctionCall;

  if (node && node.parentHtmlElement) {
    return;
  }

  // check if we are in a function call iterable Array.map() or Array.from()
  if (
    currentFunctionCall &&
    currentFunctionCall.functionName &&
    currentFunctionCall.functionName.name &&
    currentFunctionCall.functionName.name.value &&
    (currentFunctionCall.functionName.name.value === "map" ||
      currentFunctionCall.functionName.name.value === "from")
  ) {
    // check if the node has attributes
    if (node.attributes && node.attributes.length > 0) {
      // check if the nodes has an attribute "key"
      if (
        node.attributes &&
        node.attributes.filter(
          (a) => a.name && a.name.value && a.name.value === "key",
        ).length > 0
      ) {
        return;
      }
    }

    // no key present build error
    const error = buildError(
      node.start.line,
      node.start.col,
      node.end.line,
      node.end.col,
      `Missing "key" prop for element in iterator`,
      "WARN",
      "BEST_PRACTICES",
    );

    addError(error);
  }
}

good.jsx

Expected test result: no error


data.map((x) => <Hello key={x.id} />);

Array.from([1, 2, 3], (x) => <Hello key={x.id}>{x}</Hello>);

Array.from([1, 2, 3], (x) => (
	<Hello key={x.id}>
		<span>{x}</span>
	</Hello>
));

bad.jsx

Expected test result: has error


data.map((x) => <Hello />);

Array.from([1, 2, 3], (x) => <Hello />);

data.map((x) => <Hello><span>stub</span><Hello>);

Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.