I have this component Field.jsx
.
JavaScript
x
5
1
class Field extends Component {
2
constructor(props) {
3
super(props);
4
}
5
players is a list of dicts which contains structures like so:
JavaScript
1
2
1
[{"name": "Edson", "position": "Forward"} { }, { }]
2
And I have created this function to filter a list of dicts so as to display all players names based on a position:
JavaScript
1
4
1
getPlayersByPosition = (players, position) => {
2
return players.filter((player) => player.position === 'Forward');
3
}
4
And here I’m trying to display the first player ‘name’ returned by the function directly <Position> HERE </Position>
, with:
JavaScript
1
23
23
1
render() {
2
const { players } = this.props;
3
if(players){
4
return (
5
<div className="back">
6
<div className="field-wrapper">
7
<Output output={this.props} />
8
<div className="row">
9
<Position>
10
{this.getPlayersByPosition(players, 'Forward')[0]}> //does not work
11
</Position>
12
<Position>
13
{players[1].name} //works
14
</Position>
15
</div>
16
</div>
17
</div>
18
);
19
}else{
20
return null}
21
}
22
}
23
On my first <Position>
, when I try to apply the function, I’m getting:
On the second I get the value printed:
How do I fix this?
Advertisement
Answer
in React objects are not valid as a children. so when you are trying to render
JavaScript
1
2
1
{this.getPlayersByPosition(players, 'Forward')[0]}
2
it is returning the first object from the filtered array . if you do something like
JavaScript
1
2
1
{this.getPlayersByPosition(players, 'Forward')[0].name}
2
it should work