Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

({ 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading