I would like to understand why react behaves this way.
This works
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => (
<Post key={post.id} title={post.title} />
))}
</>
But this doesn't
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => {
// changes are here
if (post.id < 2) {
<Post key={post.id} title={post.title} />;
}
})}
</>
It just returns blank. No errors.
What is the reason react isn't rendering this? And what would be the best approach to only render post-1
?
The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />
. However, in the second example you give a code block (by using {}). So, you need to either add return
before <Post key={post.id} title={post.title}>
like so:
{posts.map(post => {
if (post.id < 2) {
return <Post key={post.id} title={post.title} />;
}
})}
or change the if into an && to keep the implicit return behavior:
{posts.map(post =>
(post.id < 2) && <Post key={post.id} title={post.title} />
}
You have to change it to return <Post ... />;
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