E
E
Evgeny Ivanov2021-09-30 12:45:13
React
Evgeny Ivanov, 2021-09-30 12:45:13

How does props forwarding work here?

I'm learning React from video tutorials. Apparently, the author forgot to tell something.
The code below is working, but I do not have sufficient understanding of some points.

Profile.jsx

const Profile = () => {

/*  Информация для сообщений - текст сообщений и лайки  */
let posts = [
{id: 1, message: "Пост 1", likesCount:1},
{id: 2, message: "Пост 2", likesCount:2},
]

return (
<div>
<MyPosts posts={posts} />
</div>
);
}

Everything is clear in the file above. We passed an array object as props to the MyPosts component.
In fact, they called the MyPosts function with an array argument.

MyPosts.jsx
const MyPosts = (props) =>
{

let postsElements = props.posts.map( p => <Post message={p.message} likesCount={p.likesCount} /> )

return (

<div className={css.MyPosts}>
<div className={css.posts}>
 /*  Вывод сообщений */
{postsElements}
</div>
</div>
);
}


But here everything is not clear.
The component accepts the passed array (props). That is, the data from the Profile came.
Next, something is passed to the postsElements variable. This line, its logic is not fully understood.
Yes, I see that from props there is a call to the posts object (passed data) and then they "flick"?
And inside this is an arrow function that returns the result of calling the Post component with the parameters passed.
In general, it is not entirely clear what exactly is happening there.

Well, below is the construction {postsElements} unfamiliar to me.

PS
I assumed that when an array comes in props, it will be passed to the Post component in a loop.
Those. will call it several times, for each array entry. But here is something else...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tantumus21, 2021-09-30
@logpol32

postsElementsbecomes an array of components <Post>. In this case, .mapturns each set of data from the array props.postsinto a component with this data. The array itself props.postdoes not change in any way. Read about .map
Modifying props is not a good idea

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question