Passing Properties in React

Preetish Panda
3 min readMay 28, 2016

--

In the previous post we discussed about nesting of Components and displayed ListItem custom Component inside MyTaskList Component. In this post we’ll discuss more about passing props (properties) — passing data from parent component to child component. We’ll be basically populating the content of child Component using props in this tutorial.

Props

Let’s first check out what we have done till now. Following is the code present in index file.

We’re going to communicate the individual work items present in the index.ios.js (line no. 12) file into ListItem (line no. 22) Component. Let’s get started and replace the code present at line number 22 with the following:

We’re just referring to the first element of the Tasks array. Result of Tasks[0] is assigned to the variable workitem.

Note that workitem={Tasks[0]} is the prop here and it is getting passed to ListItem Component.

This brings us to next part— receiving the prop. The ListItem needs to actually capture the data it is getting. Open up the list-item.js and delete the text present at line number 13.

Any property provided to ListItem Component will be available as this.props and we need to select a specific property — workitem. The final list-item.js file would look like the following (look at line no. 13):

Here is the result in the simulator showing the first element:

Now we’ll go through another important concept — helper function.

Helper function

Our helper function will be used to create an array of the ListItem Components for each of the tasks, because we don’t want to manually create multiple copies of ListItem Component. Following is what we’re trying to achieve (conceptually):

The helper function will expand the our MyTaskList custom Component, which currently has only one property — render. Key thing to understand here is that unlike render function, helper functions won’t be called by React by default; we need to manually call them.

Now let’s add the helper function (line 4–10).

We’re using a native JavaScript function called as map to iterate on the array. We call map on an array and pass it a function which will be called for each element of the array. Finally whatever gets returned from the function will form a new array containing ListItem Components.

Now we need to pull the Component array into the render function. Replace <ListItem workitem={Tasks[0]} /> with {this.workitems()}. Here is the updated index.ios.js code:

Here is the iOS simulator showing all the tasks:

As you can see there is a warning — “Each child in an array or iterator should have a unique “key” prop”.

As per React Native documentation, we should add unique and constant key properties to Components which are part of an array of children. Let’s add the key to arrive at the final code for index.ios.js.

Now there is no warning message:

In the next post, we’ll understand usage of npm modules.

--

--