Display value returned by function in component

Tags: ,



I have this component Field.jsx.

class Field extends Component {
  constructor(props) {
    super(props);
  }

players is a list of dicts which contains structures like so:

[{"name": "Edson", "position": "Forward"}...{...}, {...}]

And I have created this function to filter a list of dicts so as to display all players names based on a position:

getPlayersByPosition = (players, position) => {
    return players.filter((player) => player.position === 'Forward');
  }

And here I’m trying to display the first player ‘name’ returned by the function directly <Position> HERE </Position>, with:

render() {
    const { players } = this.props;
    if(players){
      return (
       <div className="back">
          <div className="field-wrapper">
            <Output output={this.props} />
            <div className="row">
              <Position>
               {this.getPlayersByPosition(players, 'Forward')[0]}> //does not work
              </Position>
              <Position> 
               {players[1].name} //works
              </Position>
            </div>
          </div>
        </div>
      );
  }else{
    return null}
  }
}

On my first <Position>, when I try to apply the function, I’m getting:

enter image description here

On the second I get the value printed:

enter image description here


How do I fix this?

Answer

in React objects are not valid as a children. so when you are trying to render

{this.getPlayersByPosition(players, 'Forward')[0]}

it is returning the first object from the filtered array . if you do something like

{this.getPlayersByPosition(players, 'Forward')[0].name}

it should work



Source: stackoverflow