Isaac Godwin Udofia
10 Nov 2022
β’
2 min read
In React as we have already seen we are often iterating over some data . Perhaps we are filtering a data set down to a specific sub-set or mapping to the DOM. Whatever it is there are a few pitfalls we need to watch out for when it comes to returning our data otherwise we might be left scratching our heads.
A frustrating example can be seen when we map a data set to some elements or components. We expect to see the or elements on screen with the data we map into them. However we see nothing.
No error, no warning no data π€¨. In this situation it is likely that you're not returning your result correctly.
For our example we will be mapping our array of foods to some elements so we can show it to the user. It should look like this:
Instead our data will appear to be missing π.
Let me show you some examples where we won't see the output that we were expecting. We are passing our array to our component and destructuring it from the prop object the same as before.
Can you spot the problem below.
Correct! Here we are not returning anything either implicitly or explicitly using the return keyword.
Let's take a look at another π.
This time we include the return keyword but what we are actually doing here is returning undefined. The code below the return statement never gets read.
There are other examples you might run into but let's take a look at the different solutions we can use.
Let's start with the explicit returns. If we move our article element in line with the return statement all is well.
See below π
We could also wrap the return elements with parenthesis like this:
Another option is to return the result implicitly which means we can forget the return statement and the function body curly braces. Check it out π.
or inline like this π.
The choice is up to you as long as you are aware of the possible pitfalls you encounter. If the data appears to be missing make sure you check your map function carefully and make sure you are actually returning correctly.
Isaac Godwin Udofia
See other articles by Isaac
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!