Skip to content
Advertisement

Unable to Map Data to Child Component

Basically I’m doing it wothout Arrow function to map all the data to Card Component but Im unable to map data to child component, but console log & manually is showing the data but not when I’m mapping.

I want to do thing without Arrow function

Please tell me what I’m doing wrong.

App Component render at index.js

import React from "react";
import CardComp from "./card.js";
import sdata from "./sdata";

sdata.map(App);

function App(val){
    // console.log(data)

    return(
        <>
        {console.log(val.first_name)}
        <CardComp src="https://picsum.photos/200/300" 
        title={val.id}
        text={val.email}
        bttext={val.gender}
        />
        </>
    )
}

export default App;

Card Component

import React from 'react'
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';


function CardComp(props) {
  return (
    <Card style={{ width: '18rem' }}>
      <Card.Img variant="top" src={props.src} />
      <Card.Body>
        <Card.Title>{props.title}</Card.Title>
        <Card.Text>
          {props.text}
        </Card.Text>
        <Button variant="primary">{props.bttext}</Button>
      </Card.Body>
    </Card>
  )
}

export default CardComp;

raw Jason Data Array

const data = [{
    "id": 1,
    "first_name": "Andriana",
    "last_name": "Goodale",
    "email": "agoodale0@nsw.gov.au",
    "gender": "Female",
    "ip_address": "82.200.197.74"
  }, {
    "id": 2,
    "first_name": "Coralie",
    "last_name": "Aisman",
    "email": "caisman1@mtv.com",
    "gender": "Female",
    "ip_address": "214.55.245.199"
  }, {
    "id": 3,
    "first_name": "Allan",
    "last_name": "Armatage",
    "email": "aarmatage2@army.mil",
    "gender": "Male",
    "ip_address": "181.180.166.43"
  }

Advertisement

Answer

You can move the mapping of data inside the component without using arrow function as:

function App(val) {
  return (
    <>
      {sdata.map(function (val) {
        return (
          <CardComp
            src="https://picsum.photos/200/300"
            title={val.id}
            text={val.email}
            bttext={val.gender}
          />
        );
      })}
    </>
  );
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement