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?
JavaScript
x
47
47
1
import React, {useState} from 'react'
2
import {Form, Button} from 'antd'
3
4
const Products = [
5
{ key: 1, value: "A", stock: 0 },
6
{ key: 2, value: "B", stock: 1 },
7
{ key: 3, value: "C", stock: 2 },
8
{ key: 4, value: "D", stock: 0 },
9
{ key: 5, value: "E", stock: 0 },
10
{ key: 6, value: "F", stock: 3 },
11
{ key: 7, value: "G", stock: 4 },
12
]
13
14
function ProductPage() {
15
16
// States
17
const [product, setProduct] = useState(1) // initial value : 1
18
19
// Handlers
20
const productChangeHandler = (event) => {
21
setProduct(event.currentTarget.value)
22
}
23
24
25
return (
26
<div style={{ maxWidth: '700px', margin: '2rem auto' }}>
27
<div style={{textAlign: 'center', marginBottom: '2rem'}}>
28
<h2>Product Soldout State</h2>
29
</div>
30
31
<Form>
32
33
{/* DropZone */}
34
<br />
35
<br />
36
<select onChange={productChangeHandler} value={product} >
37
{Products.map(item => (
38
<option key={item.key} value={item.key} >{item.value}</option>
39
))}
40
</select>
41
<Button>Upload</Button>
42
43
</Form>
44
45
</div>
46
)
47
}
export default ProductPage
Advertisement
Answer
Use the disabled
JSX property, which maps to the disabled
attribute: disabled={item.stock < 1}
In context:
JavaScript
1
4
1
{Products.map(item => (
2
<option key={item.key} value={item.key} disabled={item.stock < 1}>{item.value}</option>
3
))}
4
More minimal example:
JavaScript
1
15
15
1
const options = [
2
{value: 1, stock: 40, text: "Plenty"},
3
{value: 2, stock: 1, text: "Just enough"},
4
{vlaue: 3, stock: 0, text: "None"},
5
];
6
const Example = () => {
7
return <select>
8
{options.map((option) => (
9
<option value={option.value} disabled={option.stock < 1}>{option.text}</option>
10
))}
11
</select>;
12
};
13
14
const root = ReactDOM.createRoot(document.getElementById("root"));
15
root.render(<Example />);
JavaScript
1
4
1
<div id="root"></div>
2
3
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>