Home > other >  What is the difference between () => <ProductCard /> and () => {<ProductCard />}
What is the difference between () => <ProductCard /> and () => {<ProductCard />}

Time:11-07

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.

enter image description here

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 : enter image description here

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:)

CodePudding user response:

({ item }) => <ProductCard product={item} />

is an arrow function that returns a ProductCard component. It's basically a shorthand syntax for something like this:

({ item }) => { return <ProductCard product={item} />; }

when you use it without the return, it basically like running code without returning it, and that's why

 const renderProduct = ({ item }) => {
    <ProductCard product={item} />;
 };

doesn't render anything in your case.

  • Related