Search code examples
javascriptreactjsstatesetstate

React JS - Error when using this. state next to the component


I am receiving the following errors: 1.Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: array. Check your code at ButtonMenu.js:432. 2.Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

It appears to have an issue with this line of code:

<ProductList products={this.state.products} />

Is that not the correct way to use this? Here is the full code:

import React, {Component} from "react";  



const  ProductList =[
    {
        id:0,
        category:"accessories",
        image:"./prod_images/accessory1.jpg",
        product: "product1",
        description: "product1",
        price: 0.00
},

];

//There are 50+ of these objects. I cut them out to keep this short.

const CATEGORIES = ['All', 'Men', 'Women', 'Jerseys', 'Shirts', 'Accessories', 'Collectables'];




class ButtonMenu extends Component {
    constructor(props) {
      super(props);
      this.state = {
        products: ProductList || []
      };
    }
  
    getCategory = category => {
      const filter = ProductList.filter(d => d.category === category);
      if (filter) {
        this.setState({products: filter});
      }
    };
    render() {
      return (
       <>
          <div className="button Menu-container">
            <ProductList products={this.state.products} />
            {CATEGORIES.map(item => (
                <button
                key ={item.toString()}
                className="main-btn"
                onClick={() => this.getCategory(item.toLowerCase())}
                value={item.toLowerCase()}>
                {item}
              </button>
            ))}
          </div>
          </>
      );
    }
  }
  
  export default ButtonMenu;

Solution

  • You are trying to render an array of objects as it was a react component. That is why you are getting the error because it's something against the rules. So, instead of rendering the ProductList you probably want to do something like this:

    <div>
     {this.state.products.map((product) => {
       //here you render whatever you want to render about each product
     })}
    </div>
    

    Docs: https://reactjs.org/docs/components-and-props.html#rendering-a-component