I wanted to try product variant weight according to MRP show with react js, but it didn't work. please suggest me. I want to pass onChange() product variants weight mannualy its worked, but I want to pass value use e.target.value did not work. how do I do?
import React, { useState } from "react";
import "./App.css";
function App() {
const product = {
productName: "IndoPrimo Men's Regular Fit Cotton Casual Shirt",
productCategory: "HUMJOLI",
image: "../images/I/71ZFayjCD-L._UL1500_.jpg",
maxQty: 5,
minQty: 1,
unit: "gram",
variantNames: ["weight"],
variants: [
{ weight: 500, mrp: 100, storePrice: 80 },
{ weight: 1000, mrp: 200, storePrice: 140 },
],
productMrp: 2199,
productStoreprice: 7189,
};
const [sate, setSize] = React.useState([]);
const handleBtn = (e) => {
const id = e.target.value;
console.log(id);
const updatei̥tem = product.variants.filter((r) => {
return r.weight === id;
});
setSize(updatei̥tem);
};
return (
<div>
<select name="r" onChange={(e) => handleBtn(e)}>
{product.variants.map((i) => (
<option value={i.weight} key={i.weight}>
{i.weight}
</option>
))}
</select>
<div>
{sate?.map((i) => (
<p>{i.mrp}</p>
))}
</div>
</div>
);
}
CodePudding user response:
The strict equality operator ===
in the filter function is too strict for you case. r.weight
is a number
, and id
is a string
.
You can change it to ==
, then the type casting will be done automatically:
const updatei̥tem = product.variants.filter((r) => {
return r.weight == id;
});
CodePudding user response:
import React, { useState } from "react";
function Data() {
const product = {
productName: "IndoPrimo Men's Regular Fit Cotton Casual Shirt",
productCategory: "HUMJOLI",
image: "../images/I/71ZFayjCD-L._UL1500_.jpg",
maxQty: 5,
minQty: 1,
unit: "gram",
variantNames: ["weight"],
variants: [
{ weight: 500, mrp: 100, storePrice: 80 },
{ weight: 1000, mrp: 200, storePrice: 140 },
],
productMrp: 2199,
productStoreprice: 7189,
};
const [sate, setSize] = useState([]);
const handleBtn = (e) => {
const id = e.target.value;
/*Suggestion 1*/
const updatei̥tem = product.variants.filter((r) => {
if (r.weight === id) {
return r;
}
});
setSize(updatei̥tem);
};
return (
<div>
<select name="r" onChange={(e) => handleBtn(e)}>
{product.variants.map((i) => (
<option value={i.weight} key={i.weight}>
{i.weight}
</option>
))}
</select>
{/*Suggestion 2*/}
{sate &&
sate.map((i) => {
return <p>{i.weight}</p>;
})}
</div>
);
}
export default Data;
My suggestions, I hope it works