A-fandino
A-fandino

Reputation: 774

Props are undefined until component reloads

I want to my map through an object's array and create a table like this:

import React from "react";

export default function Scoreboard(props) {
  return (
    <div className="scoreboard">
      <table>
        {props.players.map((val, num) => {
          return (
            <tr>
              <tl>{val.id} :</tl>
              <tl>{val.name}</tl>
            </tr>
          );
        })}
      </table>
    </div>
  );
}

The problem is that props.players is undefined in the first component load.

If I change the code React reloads the component and the table finally appears.

I tried using useState and useEffect but It didn't work.

EDIT: I think that maybe the problem is that when the Scoreboard component is generated (and passed the props), the players array has not value in the parent.

Upvotes: 0

Views: 45

Answers (3)

PhantomSpooks
PhantomSpooks

Reputation: 3540

I think the way to do it with the least amount of code would be to give props a default parameter value:

import React from "react";

export default function Scoreboard(props={players:[]}) {
  return (
    <div className="scoreboard">
      <table>
        {props.players.map((val, num) => {
          return (
            <tr>
              <tl>{val.id} :</tl>
              <tl>{val.name}</tl>
            </tr>
          );
        })}
      </table>
    </div>
  );
}

I think this achieve the same results that adding conditionals in your JSX would

Upvotes: 0

Dani
Dani

Reputation: 895

You can add condition and render the data only if the props.players exists

import React from "react";

export default function Scoreboard(props) {
  return (
    <div className="scoreboard">
      <table>
        {props.players && props.players.map((val, num) => {
          return (
            <tr>
              <tl>{val.id} :</tl>
              <tl>{val.name}</tl>
            </tr>
          );
        })}
      </table>
    </div>
  );
}

Upvotes: 0

Daniel Bellmas
Daniel Bellmas

Reputation: 657

try this:

import React from "react";

export default function Scoreboard(props) {
  return (
    <div className="scoreboard">
      <table>
        {props?.players?.map((val, num) => {
          return (
            <tr>
              <tl>{val.id} :</tl>
              <tl>{val.name}</tl>
            </tr>
          );
        })}
      </table>
    </div>
  );
}

Upvotes: 1

Related Questions