no-danger-with-children

Try in Playground
react-best-practicesError ProneError

0

No tags

No CWE or CVE

This rule shows a warning when a DOM element or component is using both children and the dangerouslySetInnerHTML prop at the same time.

React will throw a warning if this rule is ignored.

This rule is similar to the react/no-danger-with-children rule from ESLint.

Ast Rule: html element


no-danger-with-children

How to write a rule
function visit(node) {
  if (!node || !node.attributes || node.attributes.length === 0) return;

  const dangerouslySetInnerHTMLAttribute = node.attributes.find(
    (a) => a.name?.value === "dangerouslySetInnerHTML"
  );

  if (!dangerouslySetInnerHTMLAttribute) return;

  const numOfChildren = node.htmlChildren?.length;

  if (!numOfChildren) return;

  const error = buildError(
    node.tag.start.line,
    node.tag.start.col,
    node.tag.end.line,
    node.tag.end.col,
    "Only set one of `children` or `props.dangerouslySetInnerHTML`",
    "WARNING",
    "BEST_PRACTICE"
  );

  addError(error);
}

double-children.jsx

Expected test result: has error

Children are set twice here

<div dangerouslySetInnerHTML={{ __html: "HTML" }}>
  Children
</div>

<Hello dangerouslySetInnerHTML={{ __html: "HTML" }}>
  Children
</Hello>

valid.jsx

Expected test result: no error

Children are only set once here

<div dangerouslySetInnerHTML={{ __html: "HTML" }} />

<Hello dangerouslySetInnerHTML={{ __html: "HTML" }} />

<div>
  Children
</div>

<Hello>
  Children
</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.