0

I am trying to implement Presentational and Container Components pattern when creating React components. So I created a presentational component with only UI elements and container component with handling data capabilities.

component.jsx

import React from "react";

const MyComponent = ({props}) => (
<div>
{props.games.map((game, index) => (
  <div key={index}>
    {game.index + 1} - {game.contestName}
  </div>
))};
</div>
);

export default MyComponent;

container.jsx

import React, { Component } from "react";
import MyComponent from "./component";

class MyContainer extends Component {
constructor(props) {
super(props);

this.state = {
  games: [
    {
      id: 1,
      categoryName: "Business/Company",
      contestName: "Name1"
    },
    {
      id: 2,
      categoryName: "Magazine/Newsletter",
      contestName: "Name2"
    },
    {
      id: 3,
      categoryName: "Software Component",
      contestName: "Name3"
    },
    {
      id: 4,
      categoryName: "Website",
      contestName: "Name4"
    }
  ]
};
}

render() {
return (
  <div>
    <MyComponent games={this.state.games} />
  </div>
);
}
}

export default MyContainer;

However, I can not render data and I get

Uncaught TypeError:

Cannot read property 'games' of undefined.

Would really appreciate your help, as two days of internet digging has not yielded positive results.

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
Donatas
  • 25
  • 1
  • 4
  • This answer explains, the solution to your problem https://stackoverflow.com/questions/44734548/what-is-the-children-prop-in-react-component-and-what-proptypes-do/44734573#44734573 – Shubham Khatri Sep 13 '17 at 10:48

3 Answers3

2
const MyComponent = ({props}) => (

When you do this, you actually do

{ props: props-received-from-parent }

You are enclosing your props in another object, remove those braces and change that line to

const MyComponent = (props) => (

and you are good to go.

Aanchal1103
  • 917
  • 8
  • 21
1

You should destructure your games instead of props:

import React from "react";

const MyComponent = ({games}) => (
<div>
{games.map((game, index) => (
  <div key={index}>
    {game.index + 1} - {game.contestName}
  </div>
))};
</div>
);

export default MyComponent;
Tholle
  • 108,070
  • 19
  • 198
  • 189
0

You can define your MyComponent class like this

class MyComponent extends Component{

    render(){
        this.xyz = this.props.games.map((item,index) => {
            return(<div key={index}>{item.id}</div>)
        })
        return(
            <div>
                {this.xyz}
            </div>
        )

    }
}

export default MyComponent;

This will also work!

Aayushi
  • 1,736
  • 1
  • 26
  • 48