Making components functional

While implementing these new components, you might have noticed that they don't have any responsibilities other than rendering JSX using property values. These components are good candidates for pure function components. Whenever you come across components that only use property values, it's a good idea to make them functional. For one thing, it makes it explicit that the component doesn't rely on any state or lifecycle methods. It's also more efficient, because React doesn't perform as much work when it detects that a component is a function.

Here is the functional version of the article list component:

import React from 'react';
import ArticleItem from './ArticleItem';

export default ({ articles, onClickToggle, onClickRemove }) => (
<ul>
{articles.map(i => (
<ArticleItem
key={i.id}
article={i}
onClickToggle={onClickToggle}
onClickRemove={onClickRemove}
/>
))}
</ul>
);

Here is the functional version of the article item component:

import React from 'react';

export default ({ article, onClickToggle, onClickRemove }) => (
<li>
{/* The "onClickToggle()" callback changes
the state of the "MyFeature" component. */}
<a
href={`#${article.id}`}
title="Toggle Summary"
onClick={onClickToggle.bind(null, article.id)}
>
{article.title}
</a>
&nbsp;
{/* The "onClickRemove()" callback changes
the state of the "MyFeature" component. */}
<a
href={`#${article.id}`}
title="Remove"
onClick={onClickRemove.bind(null, article.id)}
>

</a>
<p style={{ display: article.display }}>{article.summary}</p>
</li>
);

Here is the functional version of the add article component:

import React from 'react';

export default ({
name,
title,
summary,
onChangeTitle,
onChangeSummary,
onClickAdd
}) => (
<section>
<h1>{name}</h1>
<input
placeholder="Title"
value={title}
onChange={onChangeTitle}
/>
<input
placeholder="Summary"
value={summary}
onChange={onChangeSummary}
/>
<button onClick={onClickAdd}>Add</button>
</section>
);

Another added benefit of making components functional is that there's less opportunity to introduce unnecessary methods or other data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.100.48