style-prop-object

Try in Playground
react-best-practicesBest PracticeInformational

0

No tags

No CWE or CVE

This rule requires that the value of the style prop be an object or a variable that is an object.

View a similar rule from ESLint, react/style-prop-object

Ast Rule: html element


style-prop-object

How to write a rule
function visit(node, filename, code) {
  if (!node) return;

  // if there are no attributes, skip it
  if (node.attributes.length === 0) return;

  // get the style prop object
  const styleProp = node.attributes.find(attribute => attribute.name?.value === 'style')

  // if the prop is a string, build an error
  if (!styleProp.value?.elements) {
    const error = buildError(
      styleProp.name.start.line,
      styleProp.name.start.col,
      styleProp.name.end.line,
      styleProp.name.end.col,
      `Style prop value must be an object`,
      "WARNING",
      "BEST_PRACTICE"
    )
    addError(error)
  } else {
    // if the style prop is an object, skip it
    if (styleProp.value?.elements[0]?.astType === "object") return;

    // if the element isn't an object, build an error
    // TODO
  }
}

incorrect.jsx

Expected test result: has error

Incorrect style prop usage

<div style="color: 'red'" />

<div style={true} />

<Hello style={true} />

const styles = true;
<div style={styles} />

correct.jsx

Expected test result: no error

Correct usage of style prop

<div style={{ color: "red" }} />

<Hello style={{ color: "red" }} />

const styles = { color: "red" };
<div style={styles} />
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.