In my Class component, I have a list of 9 dictionaries as props
:
[{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Each dictionary key, value structure:
{name:'John', position:'fwd'}, {name:'Peter', position:'mid'}, {name:'Bill', position:'def'},...
Now I need to extract dictionary ‘name’ values and display them as text in my component.
For every group of three rows, the value must satisfy the condition of its unique ‘position’, that is, 3 names for ‘fwd’, then 3 names for ‘mid’, then names 3 for ‘def’, until the list is emptied.
This is the render:
render() { const { players } = this.props; if(players){ return ( <div className="app"> <div className="pos-wrapper"> <div className="row"> <Position>FWD Name 1</Position> <Position>FWD Name 2</Position> <Position>FWD Name 3</Position> </div> <div className="row"> <Position>MID Name 1</Position> <Position>MID Name 2</Position> <Position>MID Name 3</Position> </div> <div className="row"> <Position>DEF Name 1</Position> <Position>DEF Name 2</Position> <Position>DEF Name 3</Position> </div> </div> </div> ); } else{ return null } } }
Examples of expected result:
FWD NAME 1 -> John ... ... MID NAME 1 -> Peter ... ... DEF NAME 1 -> Bill ... ...
How do I extract the values using that condition and keeping the structure above?
Advertisement
Answer
I guess this is how i would do it.
render() { const { players } = this.props; if(players){ return ( <div className="app"> <div className="pos-wrapper"> {players.map((player,i)=>( <div key={i} className="row"> { { 'fwd': <Position>FWD Name {player.name}</Position> , 'mid': <Position>MID Name {player.name}</Position>, 'def': <Position>DEF Name {player.name}</Position> , }[player.position] } </div> ))} </div> </div> ); } else{ return null } }
Edited: It doesn’t feel like it’s an good idea but i guess following would give you the correct output
render() { const { players } = this.props; if(players){ return ( <div className="app"> <div className="pos-wrapper"> <div className="row"> {players.map((player,i)=>( {(player.position==="fwd")? <Position key={i}>FWD Name {player.name}</Position> } ))} </div> <div className="row"> {players.map((player,i)=>( {(player.position==="mid")? <Position key={i} >MID Name {player.name}</Position> } ))} </div> <div className="row"> {players.map((player,i)=>( {(player.position==="def")? <Position key={i} >DEF Name {player.name}</Position> } ))} </div> </div> </div> ); } else{ return null } }