Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to solve the ` Component should be written as a pure function ` error in eslint-react?

Tags:

reactjs

eslint

class Option extends React.Component {   constructor(props) {     super(props);     this.handleClickOption = this.handleClickOption.bind(this);   }   handleClickOption() {     // some code   }   render() {     return (       <li onClick={this.handleClickOption}>{this.props.option}</li>     );   } } 

I use eslint-config-airbnb to check the above code and it show me an error msg like Component should be written as a pure function .

So how to change the above component to pure function?

Thanks for your help.

like image 849
Liu Dongyu Avatar asked Mar 07 '16 08:03

Liu Dongyu


People also ask

How do you make a functional component pure in react?

To create a pure functional component in React, React provides a React. memo() API. Using the React. memo() API, the React functional component can be wrapped as follows to get React Pure Functional Component.

What is a react pure component?

A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.

What is functional component in Reactjs?

What are the functional component and class component in React? Functional component is just a simple javascript function; it accepts the data in the form of props and returns the react element. Whereas the class component will be created using the class keyword, and it extends the React.

What is a stateless functional component?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.


1 Answers

React 0.14 introduced pure function components.

This should be the preferred option for all stateless components.

function Option({ onClick, option }) {     return (         <li onClick={onClick}>             {option}         </li>     ); } 
like image 166
David L. Walsh Avatar answered Sep 23 '22 13:09

David L. Walsh