Home > Net >  Why the return type of react code is NaN?
Why the return type of react code is NaN?

Time:10-27

I'm newbie in React and after searching unfortunately I didn't find my solution. This code below is my main component and saved as product.jsx:

import React, { useState } from "react";


const Product = ({countt,productName,children}) => {
  const [count, setCount] = useState(countt);

  return (
    <>
      <span className="m-2 text-info">{productName}</span>
      <span className="m-2 badge bg-primary">{format()}</span>
      <button onClick={handleIncrement} className="m-2 btn btn-sm btn-success">
         
      </button>
      <button onClick={handleDecrement} className="m-2 btn btn-sm btn-warning">
        -
      </button>
      <button className="m-2 btn btn-sm btn-danger">delete</button>
      <img
        src="https://picsum.photos/200"
        style={{ borderRadius: "50px" }}
        alt="#"
      />
      {children}
    </>
  );
  function handleIncrement() {
    setCount(count   1);
  }

  function handleDecrement() {
    setCount(count - 1);
  }

  function format() {
    if (count === 0) {
      return "zero";
    } else {
      return count;
    }
  }
};

export default Product;

and this is my products.jsx component:

import React, { useState } from "react";
import Product from "./product";

const Products = () => {
  const [products, setProducts] = useState([
    { id: 1, productName: "Laptop", countt: 2 },
    { id: 2, productName: "Phone", countt: 3 },
    { id: 3, productName: "Console", countt: 7 },
  ]);

  return (
    <>
      {products.map((p, index) => {
        <Product
          key={index}
          productName={p.productName}
          count={p.count}
        ></Product>;
      })}
    </>
  );
};

export default Products;

these codes work well but the problem is when I click on a button it will shown NaN.

I tried different ways and I only want to do it in functional way.

CodePudding user response:

count to countt in child components. (or otherway around. Just keep it same)

{ id: 1, productName: "Laptop", countt: 2 },

 countt={p.countt}

Also, parenthesis are missing inside the map

 return (
    <>
      {products.map((p, index) => (
        <Product
          key={index}
          productName={p.productName}
          countt={p.countt}
        ></Product>;
      ))}
    </>
  );

Demo

  • Related