Search code examples
javascriptreactjsarraysmultidimensional-arrayreact-state-management

How could I set/update a prop passed down to a React component from user input


I have values in an array of objects that I wish to display as scoreBoard showing scores of two players after a number of sets in a game. I wish to have them in separate rows for the players. Thank you in anticipation.

The picture below shows scores after two sets. How can I print the scores of each player in a separate row on the DOM? Eg.

"player1Scores": 4 8 12

"player2Scores": 5 18 22

import React from "react"
import ReactDOM from "react-dom"
export default funtion App(){
    const [players, setPlayers] = React.useState([{name: "Obi",       
    age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi", 
    age: 47, achievements: [8, 10, 12, 21]}]);
    const scores = players.map((player) => (player.achievements.map( (score, ind) => (<h2 key={ind}>{score}</h2>)
    ))
    return ( {scores}  )
}
ReactDOM.render(<App />, document.getElementById("root"))

Solution

  • I solved the problem by passing the array, player.achievements to a component and mapped through it.

    const [players, setPlayers] = React.useState([{name: "Obi",       
    age: 44, achievements: [12, 4, 16, 28]}, {name: "Chiadi", 
    age: 47, achievements: [8, 10, 12, 21]}]);
    
    const scores = players.map((player) => (
    <ScoreComponent scores ={player.achievements}/>)
    )
    

    I was then able to map through props.scores in the child component (ScoreComponent) and have the achievements or scores displayed."