Home > database >  react: how to call an object method as react child
react: how to call an object method as react child

Time:01-29

I have tried calling it as a function "item.d_price()" hence, error:"item.d_price is not a function"

data.js file

export const products = [
{ 
  id: 1,
  discount: 50,
  icon: <LikeIcon/>,
  image: noImage,
  desc: "PS5 PlayStation 5 and Disk Version Game with pad...",
  price: 560000,
  d_price: function(){return(this.price - (this.discount / 100 * this.price));}
}
...
]

sales.jsx file

  import { products } from "../data";

  const Sales = () => {

  return (
  <div className="sales">
  <div className="sales-direction">
    <div className="sales-container">
      <div className="s-header">
        <h6> Fash Sales </h6>
      </div>
      <div className="s-stories">
        <ul>
          {products?.map((item)=>{
            return(
              <li key={item.id}>
                <div className="product-card">
                  <div className="card-details">
                    <img src={item.image} alt="" height={"80px"} width={"80px"} />
                    <h6>{item.desc}</h6>
                    <h5>
                      <p>&#x20A6;{item.d_price()}</p>
                      <span>&#8358;{item.price}</span>
                    </h5>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </div>
    </div>
  </div>
  </div>
);
 };

export default Sales;

I also tried getting it as "item.d_price", error: "Functions are not valid as a React child"

I also tried placing "this.price - (this.discount / 100 * this.price)" instead of the iterated "item.d_price", error: not displaying and showing "NaN" on the console

CodePudding user response:

The main issue

You must provide a react element around the list to make it work. You can either use the template <> tag or in this case, since you are using <li> use <ul>.

Second issue

data.js file must be data.jsx. Also make sure, that the <LikeIcon> is imported or defined somewhere.

Working example

See here: https://codesandbox.io/s/hopeful-rain-dzxi0u?file=/src/component/product-list.jsx

  • Related