Skip to content
Advertisement

props are not working when using map method in react.js

props are passing fine when we are passing them as a whole array of objects but it is not working when I am passing the props by traversing through the array using map function.

import { React, useEffect, useState } from "react";

import axios from "axios";

import "./Home.css";
import Cardimg from "./Cardimg";
const Home = props => {
    return (
        <>
            <div className="header">PHOTO GALLERY</div>
            <div className="photos">
                {props.data?.map(e => {
                    <Cardimg data={e.ImgUrl}></Cardimg>;
                })}
            </div>
        </>
    );
};

export default Home;

in the above code props are passing when I am passing manually in Cardimg component…but as soon as I start using map then it doesn’t work…like the props are not reaching the component.

below is my Cardimg component

import React from 'react'

const Cardimg = (props) => {
  console.log(props.data);
    return (
    <div>{props.data}</div>
  )
}

export default Cardimg

Advertisement

Answer

You need to return the Cardimg component inside map callback function.

Either like this

{
    props.data?.map(e => {
        return <Cardimg data={e.ImgUrl}></Cardimg>;
    });
}

Or like this

{
    props.data?.map(e => <Cardimg data={e.ImgUrl}></Cardimg>)
}
Advertisement