skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. 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 { } in renderItem so if you wanna render the component then you have to write return word like this

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

    Thanks!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search