no-string-refs

Try in Playground
react-best-practicesBest PracticeWarning

0

No tags

No CWE or CVE

There were two ways supported by React to refer to components.

The first way, providing a string identifier, is now considered legacy in the official documentation.

The documentation now prefers a second method -- referring to components by setting a property on the this object in the reference callback or setting the ref value given from React.useRef.

View a similar ESLint, react/no-string-refs.

Ast Rule: html element


no-string-refs

How to write a rule
function getStringValue(value) {
  return value?.replace(/^\"/g, "").replace(/\"$/g, "") || ""
}

function getPropStringValue(value) {
  if (value.elements) {
    return getStringValue(value?.elements[0]?.value)
  } else {
    return getStringValue(value?.value)
  }
}

function visit(node, filename, code) {
  if (!node || !node.tag) return;

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

  // find the ref prop
  const refProp = node.attributes.find(attribute => attribute.name?.value === 'ref')
  if (!refProp) return

  const refPropString = getPropStringValue(refProp.value)

  if (refProp.value?.astType === "string" && refPropString) {
    const error = buildError(
      refProp.name.start.line,
      refProp.name.start.col,
      refProp.name.end.line,
      refProp.name.end.col,
      `Using string literals in ref attributes is deprecated`,
      "WARNING",
      "BEST_PRACTICE"
    )
    addError(error)
    return;
  }

  if (refProp.value?.astType === "sequence" && ["`", "\"", "'"].includes(refPropString[0])) {
    const error = buildError(
      refProp.name.start.line,
      refProp.name.start.col,
      refProp.name.end.line,
      refProp.name.end.col,
      `Using string literals in ref attributes is deprecated`,
      "WARNING",
      "BEST_PRACTICE"
    )
    addError(error)
  }
}

incorrect.jsx

Expected test result: has error

var Hello = createReactClass({
 render: function() {
  return (
		<div>
			<div ref="hello">Hello, world.</div>
			<div ref={'morning'}>Good morning</div>
			<div ref={`night`}>Good night</div>
		</div>
	)
 }
});

correct.jsx

Expected test result: no error

var Hello = createReactClass({
  componentDidMount: function() {
    var component = this.hello;
    // ...do something with component
  },
  render() {
    return <div ref={(c) => { this.hello = c; }}>Hello, world.</div>;
  }
});

correct-useref.jsx

Expected test result: no error

import { useRef } from 'react';

function App() {
	const ref = useRef()
	
	return (
		<div ref={ref}>
			Hello World
		</div>
	)
}
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.