Passing state down as props in React

3.1k Views Asked by At

I have my main component called App.

App pulls in the Table component like so:

<Table
  players={players}
/>

players is initially defined in the App component's state as an empty array but inside my Table component I do this:

console.log(this.props.players, 'players');

Why would I get undefined?

I also have this inside my App component:

render() {
   const { players, matches } = this.state;
2

There are 2 best solutions below

0
On BEST ANSWER

Regarding my comment in your question you need to do something like this:

<Table
  players={this.state.players}
/>

This way you are getting players from inside your state. Without "this.state" you will receive and undefined error

0
On

You should reference the object / array from the state like this

this.props.state.players` 

Or you can use the Destructuring assignment of ES6 like so:

 const { players } = this.state;

Example:

const Table = ({ players }) => {
  return (
    <table>
      <thead>
        <th>Name</th>
      </thead>
      <tbody>
        {
          players.map(player => {
            return (
              <tr>
                <td>
                  {player}
                </td>
              </tr>
            )
          })
        }
      </tbody>
    </table>
  );
};

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      players: ['john', 'alex', 'chris', 'dan']
    };
  }

  render() {
    const { players } = this.state;
    return (
      <div>
        <Table players={players} />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Edit
As a followup to your updated question, it really depends on how you set up your Table component.

  • If its a stateless component you should be able to access the players directly without using this.props.players.
  • If its a class component then it should be working as expected but maybe you have other piece of code that may cause this behavior.

You didn't share enough code for us to know.