Home > Back-end >  ReactJS dynamically get products by category from database
ReactJS dynamically get products by category from database

Time:09-28

I retrieve the categories from the database. Retrieving the information from my API. When clicking on a category it needs to show all the products in that category retrieved from my API.Menu page showing all categories.

I tried with onclicks but it didn't work. Any suggestions?

CodePudding user response:

you should add an onClick callBack that will fetch the products of the clicked category,

getProducts(id){
    // your Logic, api call, update state ...
}

<Card onClick={ id => getProducts(categories.id)} ....

CodePudding user response:

Do you want see all products when you click Card component? If you try put onClick in a own homemade component it doesn't work. Only fires event in plain html components. I dunno how is your Card component but I'll show this suggestion...

class Card {

  (...)

  render(){
    return <div onClick={this.props.onClick}>{...}</div>
  }

}
class Menu {

  (...)

  render(){
    return (
      <div>
        ...
        <Card onClick={() => getProducts(category.id)} ...
        ...
      </div>
    );
  }

}

Other solution is wrapping a div on Card component that fires onClick

class Menu {

  (...)

  render(){
    return (
      <div>
        ...
        <div onClick={() => getProducts(category.id)}>
          <Card...
        </div>
        ...
      </div>
    );
  }

}
  • Related