When the stock value in the Product array is less than 0 or 1, I want to disable that value in the options so that it cannot be selected.(disable =true) And if product stock is greater than 0, I want to be able to select that value.(disable =false) What should I do?
import React, {useState} from 'react'
import {Form, Button} from 'antd'
const Products = [
{ key: 1, value: "A", stock: 0 },
{ key: 2, value: "B", stock: 1 },
{ key: 3, value: "C", stock: 2 },
{ key: 4, value: "D", stock: 0 },
{ key: 5, value: "E", stock: 0 },
{ key: 6, value: "F", stock: 3 },
{ key: 7, value: "G", stock: 4 },
]
function ProductPage() {
// States
const [product, setProduct] = useState(1) // initial value : 1
// Handlers
const productChangeHandler = (event) => {
setProduct(event.currentTarget.value)
}
return (
<div style={{ maxWidth: '700px', margin: '2rem auto' }}>
<div style={{textAlign: 'center', marginBottom: '2rem'}}>
<h2>Product Soldout State</h2>
</div>
<Form>
{/* DropZone */}
<br />
<br />
<select onChange={productChangeHandler} value={product} >
{Products.map(item => (
<option key={item.key} value={item.key} >{item.value}</option>
))}
</select>
<Button>Upload</Button>
</Form>
</div>
)
}
export default ProductPage
CodePudding user response:
Use the disabled
JSX property, which maps to the disabled
attribute: disabled={item.stock < 1}
In context:
{Products.map(item => (
<option key={item.key} value={item.key} disabled={item.stock < 1}>{item.value}</option>
))}
More minimal example:
const options = [
{value: 1, stock: 40, text: "Plenty"},
{value: 2, stock: 1, text: "Just enough"},
{vlaue: 3, stock: 0, text: "None"},
];
const Example = () => {
return <select>
{options.map((option) => (
<option value={option.value} disabled={option.stock < 1}>{option.text}</option>
))}
</select>;
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>