i am new to react native, i am programmin my first project and i have a really simple question.
I have a Screen that shows the data of a product, the data are fetch from a url Here is a sample of the fetch object
{"id":"2-1","product_name":"sample product","price":"0.29","qty_step":"1","mm":"item","tax":"24.00","large_box_discount":8,"mpn":"2221","manufacturer_name":"company","weight":"0.027","ogkos_m3":"0.00011697","barcode":"002000100001","colors":["red","blue"],"sizes":null
}
The problem is when i try to render color and sizes.
{/*colors*/}
<View>
if (data!=undefined && data.colors!=undefined && data.colors!=null)
{
data.colors.map( (item, index) => (
<View style={styles.AvailabilityWrapper}>
<Text>{item}</Text>
</View>
))
}
</View>
{/*sizes*/}
<View>
if (data!=undefined && data.sizes!=undefined && data.sizes!=null && data.sizes!="")
{
data.sizes.map( (item, index) => (
<View style={styles.AvailabilityWrapper}>
<Text>{item}</Text>
</View>
))
}
</View>
In case of sizes I get undefined is not a function but i have check if is undefined or null or empty
Is my if statement wrong ? What am i doing wrong ?
Any help appreciated
CodePudding user response:
This syntax:
<View>some text</View>
renders plains text.
This syntax:
<View>{ 4 > 3 ? "F" : "K" }</View>
evaluates whatever is in the braces.
You will want to write something like this instead.
<View>
{(data?.sizes || []).map((item) => { ... })}
</View>
Btw, a more general pattern for conditional rendering looks like this
<View>
{test
? <ComponentThatShouldOnlyBeRenderedWhenTestIsTruthy />
: null}
</View>
CodePudding user response:
The MAP function expects a return statement in order to display the contents(JSX) written inside that function. So add a return before your View tag.
Your if loop is promising however you could it write it better in this way.
if(data && data.size && data.size.length > 0)
. I would recommend this as it covers all cases.RULE: You cannot use if loops inside your render function. A quick fix to this is given in the code below.
Check this code:
{/*colors*/}
<View>
{
data &&
data.colors &&
data.colors.length > 0 &&
data.colors.map((item, index) => {
return <View style={styles.AvailabilityWrapper}>
<Text>{item}</Text>
</View>
})
}
</View>
{/*sizes*/}
<View>
{
data &&
data.sizes &&
data.sizes.length > 0 &&
data.sizes.map((item, index) => {
return <View style={styles.AvailabilityWrapper}>
<Text>{item}</Text>
</View>
})
}
</View>
If my answer helps you out, please upvote it as well as mark it as the answer so others can benefit from this as well!!