Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

const Header = React.createClass({
  contextTypes: {
    router: React.PropTypes.object.isRequired,
  },

  render() {
    return (
        <li className={this.context.router.isActive('a') ? 'active' : ''}>
          <Link to="/a/">A</Link>
        </li>
        <li className={this.context.router.isActive('b') ? 'active' : ''}>
          <Link to="/b/">B</Link>
        </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 824
Veljko Simic Avatar asked Jun 02 '16 17:06

Veljko Simic


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 are pure components react?

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 stateless functional components?

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

When you have a "dumb" component (no internal state, lifecycle methods, etc.), you may write it as a simple javascript function as opposed to using React.CreateClass or extending React.Component.

Check out the docs here for general information on pure functions as components and here for information specific to context.

So in your case:

function Header(context) {
  return (
    <li className={context.router.isActive('a') ? 'active' : ''}>
      <Link to="/a/">A</Link>
    </li>
    <li className={context.router.isActive('b') ? 'active' : ''}>
      <Link to="/b/">B</Link>
    </li>
  );
}

Header.contextTypes = {
  router: React.PropTypes.object.isRequired,
}
like image 158
aw04 Avatar answered Nov 09 '22 06:11

aw04