46 lines
1.6 KiB
Plaintext

== Why is this an issue?
Referring to `this` in React functional components would be an error because the components are just regular JavaScript functions
and do not have an object associated with them. Functional components receive their props as a first argument to the component function,
so you can access them directly, and it is a common practice to destructure them right away.
[source,javascript]
----
function UserProfile({firstName, lastName}){
return (
<div className="user">{firstName} {lastName}</div>
);
}
----
React also supports legacy class-based components, where `this` keyword refers to the component instance object, but this style of writing components is no longer recommended, and mixing it with functional components will lead to errors.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
function MyComponent(props){
const foo = this.props.bar; // Noncompliant: remove 'this'
return (
<div>{foo}</div>
);
}
----
To fix the issue, remove references to `this` from your functional component code. Make also sure you are not mixing functional and class-based component styles.
[source,javascript,diff-id=1,diff-type=compliant]
----
function MyComponent({bar}){
const foo = bar;
return (
<div>{foo}</div>
);
}
----
== Resources
=== Documentation
* React Documentation - https://react.dev/learn/your-first-component#defining-a-component[Defining a Component]
* React Documentation - https://react.dev/learn/passing-props-to-a-component[Passing Props to a Component]
* React Documentation - https://react.dev/reference/react/Component[Legacy class components]