So I have faced an interesting thing in my React Native Code. Can you guys explain why it ‘ s happening like that?
import React, { useState, useEffect } from "react";
import { SafeAreaView, Text, FlatList } from "react-native";
import config from "../../../config";
import axios from "axios";
import ProductCard from "../../components/ProductCard/ProductCard";
const Products = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
const { data: productData } = await axios.get(config.API_URL);
setData(productData);
};
const renderProduct = ({ item }) => <ProductCard product={item} />;
return (
<SafeAreaView>
<FlatList data={data} renderItem={renderProduct} />
</SafeAreaView>
);
};
export default Products;
İn the ProductCard component I am basically formating output to look nice like below. There is no magic over there.
Then I want you to guys look at renderProduct function
when I code it like that with curly braces :
const renderProduct = ({ item }) => {
<ProductCard product={item} />;
};
the output is being like below :
I couldn’t understand why Honestly. what is the magic with curly braces?
İf this explanation is not enough just tell me to add other things:)
2
Answers
is an arrow function that returns a ProductCard component. It’s basically a shorthand syntax for something like this:
when you use it without the return, it basically like running code without returning it, and that’s why
doesn’t render anything in your case.
Because in the First case you have not written
{ }
so that’s gonna return the component directly.But in the second case you have written the
{ }
inrenderItem
so if you wanna render the component then you have to writereturn
word like this({ item }) => { return <ProductCard product={item} />; }
Thanks!!