claudiopb
claudiopb

Reputation: 1100

ReactJs - passing props to a child component in a bit more advanced way

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

{
  "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"   
    },
    {   
      "name": "Character4",
      "punch":21,
      "kick":18,
      "special":2,
      "image":"character4"   
    }
  ]
}

So I have this parent component that is fetching the data to children components:

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">      
        <Player data={this.state.characters}/>
        <Player data={this.state.characters}/>
      </div>
    )
  }
}


export default Stage

Each <Player> component is receiving the same data. I would like to distribute the data divided for each component. For example, I have 4 characters and each component might receive 2 characters in a random way. For example to be more clear:

player 1: character1, character2 or character2, character4 or character3, character2 etc...

the same thing for player 2

each player might NOT have repeated characters. How do I solve it?

Here is a <Player> component code

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

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

export default Player

Upvotes: 0

Views: 97

Answers (5)

faizan baig
faizan baig

Reputation: 1303

You can simply do it by adding a new state called player1 and player2, create a new array and pass it to the respective component.

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

  componentDidMount() {
    const shuffled = data.characters.sort(() => 0.5 - Math.random());
    const player1 = shuffled.slice(0, 2);
    const player2 = shuffled.slice(2,4);
    this.setState({
      player1,
      player2,
    })  
  }

  render() {
    return (
      <div className="stage">      
        <Player data={this.state.player1}/>
        <Player data={this.state.player2}/>
      </div>
    )
  }
}

Upvotes: 2

Telepresence
Telepresence

Reputation: 629

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

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

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

  //function to get random list of objects
  foo(characters) {
    let randomNums = [];
    for (let i = 0; i < characters.length; i++) {
      randomNums.push(i);
    }
    let ind_1 = Math.floor(Math.random() * characters.length);
    randomNums.splice(ind_1, 1);
    let ind_2 = Math.floor(Math.random() * (characters.length - 1));
    ind_2 = randomNums[ind_2];
    console.log(ind_1);
    return [characters[ind_1], characters[ind_2]];
  }

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

  render() {
    return (
      <div className="stage">
        <Player data={this.foo(this.state.characters)} />
        <Player data={this.foo(this.state.characters)} />
      </div>
    );
  }
}

Upvotes: 0

Error Yatish
Error Yatish

Reputation: 106

claudiobitar you will achieve this by below changes

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

var data = require('./db.json');
let random = Math.floor(Math.random() * 4) + 1

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

    componentDidMount() {

        let {set1, set2} = this.state

        while (set1.length < 2) {
            !set1.includes(random) && this.setState({set1: [...set1, data.characters[random]]})
            random = Math.floor(Math.random() * 4) + 1
        }

        while (set2.length < 2) {
            !set2.includes(random) && this.setState({set2: [...set2, data.characters[random]]})
            random = Math.floor(Math.random() * 4) + 1
        }

        /*this.setState({
            characters: data.characters
        })*/
    }

    render() {

        let {set1, set2} = this.state

        return (

            <div className="stage">
                <Player data={this.state.set1}/>
                <Player data={this.state.set2}/>
            </div>
        )
    }
}


export default Stage

Upvotes: 1

Edison Junior
Edison Junior

Reputation: 320

try to divide you data before send to sub component. one way is, create 1 list with 2 sublist, that sublist will be send to sub component Player1 and Player2. try to distribute your character data in 2 sub lists in position 0 and 1 using a random number.

const lists = [[], []]
for (var i=0; i<(this.state.characters.lenght); i++) {
  const rand = Math.floor(Math.random() * 1);
  lists[rand].push(this.state.characters[i]) 
}

with that, you will be able to divide your list, but the next step is divide half for each side.

i hope it useful, i will keep trying here.

Upvotes: 0

Error Yatish
Error Yatish

Reputation: 106

    let a1= [], a2 = [], random = Math.floor(Math.random()*4) +1;

    while(a1.length < 2){
      !a1.includes(random) && a1.push(random)
      random = Math.floor(Math.random()*4) +1
    }

    while(a2.length < 2){
      !a1.includes(random) &&a2.push(random)
      random = Math.floor(Math.random()*4) +1
    }

console.log(a1, a2)

result ==> a1= [2,4] , a2 = [1,3] //randomly changing

Upvotes: 0

Related Questions