0

I am trying to separate the logic from class component to container component, so that class component only takes the responsibility of rendering html. So, I have two components here one is Home which is a class component and another is Home Container which holds the code for Home component i.e, mapStateToProps and mapDispatchToProps.

Here are the files: Home.js:

 render(){
        // Maps over 'items'
        let itemList = this.props.items.map((item) => {
            return (
                <div className="card" key={item.id}>
                    <img className="card-img-top" src={item.img} alt={item.title} />
                    <div className="card-body">
                        <span className="card-title">{item.title}</span>
                        <span to="/" onClick={() => {this.handleClick(item.id)}}><i className="material-icons">add</i></span>
                    </div>

                    <div className="card-content">
                        <p>Price: {item.price}</p>
                        {/* <p>{item.quantity}</p> */}
                    </div>

                </div>
            )
        })
        return(
            <div className="container">
                <h3 className="text-center">Our items</h3>
                <div className="box">
                    {itemList}
                </div>
            </div>
        )
    }

which gets the props from container component and that is

HomeContainer.js:

class HomeContainer extends React.Component {
    render(){
        return(
            <div>
                <Home items={this.props.items}/>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        items: state.items
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        addToCart: (id) => {dispatch(addToCart(id))}
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(HomeContainer)

and I am passing props to the Home in the HomeContainer.

When I am trying to access those props in the Home component by mapping over the items I am getting Cannot read property of undefined. How can I solve this issue.

Gowthamss
  • 191
  • 1
  • 2
  • 13

0 Answers0