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.
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.
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.
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.
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,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With