ESLint is giving me this error on a react project.
ESLint - Component should be written as a pure function (react prefer/stateless function)
It points to the first line of the component.
export class myComponent extends React.Component {
render() {
return (
//stuff here
);
}
}
How do I get rid of this error?
If all you're doing is rendering a jsx template, and not declaring state with
constructor(props)
, then you should write your component as a pure function of props, and not use theclass
keyword to define it.ex.
And in app.js file just import this component as we do for class like
and call as
It will work for sure.
You will get this error only when your class does not have any life cycle method or constructor. To solve this either you have to disable the lint property or make it as a pure function or create constructor for the class.
Write your component as a stateless function:
There are actually two styles of defining components in React: Functional components (which are just functions from props to a React component) and class components.
The main difference between them is that class components can have
state
and lifecycle methods such ascomponentDidMount
,componentDidUpdate
, etc.Whenever you don't need state of lifecycle methods, you should write your component as a stateless function, as stateless components are in general easier to reason about.
To write a functional component, you write a function that takes a single argument. This argument will receive the component's props. Consequently, you don't use
this.props
to access the component's props - you just use the function's argument.Two choices.
Temporarily disable warning
(Untested; and there are multiple ways to do this.)
Use a pure stateless component
The return value is what will be rendered (e.g., you're basically writing class-based component's
render
method:(Or use non-ES6 notation if that's your thing.)
For components like this with no other supporting logic I prefer the implicit return, e.g.,
This is a matter of preference. I would say that you should follow React naming conventions, though, and keep all components starting with an upper-case letter.
ESLint may complain about missing parens around a multi-line JSX expressions, so disable that rule or use parens.
If you need props, they're passed in as the argument to the function:
And you can destructure in the parameter as usual for convenience:
This can make the implicit return a little easier if you were using local vars. You'll get an ESLint warning about missing
PropTypes
unless you declare them; since it's not a class you cannot simply usestatic propTypes
in the class, they must be attached to the function (which many people prefer anyway).