claudiopb
claudiopb

Reputation: 1090

ReactJs - creating a dynamic list

I'm making a card game. I have this json db:

{
  "characters": [   
    {    
      "name": "Character1",
      "punch":12,
      "kick":12,
      "special":15,
      "image":"character1"

    },
    {    
      "name": "Character2",
      "punch":13,
      "kick":11,
      "special":15,
      "image":"character2"  
    },         

    {   
      "name": "Character3",
      "punch":20,
      "kick":19,
      "special":10,
      "image":"character3"   
    }
  ]
}

I have this parent component that fetches the json data to pass for a child component. The data is fetched successfully.

import React, { Component } from 'react'
import Player from './Player'

var data = require('./db.json');

class Stage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      characters: []
    }
  }

  componentDidMount() {
    this.setState({
      characters: data.characters
    })  
  }

  render() {
    return (

      <div className="stage">
      {console.log(this.state.characters)}
        <Player data={this.state.characters}/>
        <Player data={this.state.characters}/>
      </div>
    )
  }
}


export default Stage

Now I want to render each card for each character inside this component in a dynamic <li>. For example, I have 3 characters so I want to render 3 cards. Each one that matches for a character. How can I do it? I want to pass the properties for the <Card> component to

import React from 'react'
import Card from './Card'   

const Player = (props) => { 
  return (
    <div className="player">     
      <Card/>  
    </div>
  )
}


export default Player 

Upvotes: 0

Views: 506

Answers (2)

Adnan
Adnan

Reputation: 1707

Simply use .map() function to loop every item of an array.

.map()

  {data.map((item, i) => (     
    <Card key={i} name={item.name}/>  
  ))}

Upvotes: 1

Matt Way
Matt Way

Reputation: 33151

For this you want to use .map(). Basically you take an array, and return a set of react components from that array. For example:

const Player = ({ data }) => { 
  return (
    <div className="player">
      {data.map((character, i) => (     
        <Card key={i} name{character.name}/>  
      ))}
    </div>
  )
}

Here I have passed the name key down into each card, but you can pass whatever you want (including the entire character object if that makes sense).

Also, I would rename data to characters as this makes more sense. And I would set a default to the prop to be an empty array.

Upvotes: 2

Related Questions