hi guys i want to update select options when user add new category can anyone tell me how to do this ?
JavaScript
x
26
26
1
import React, { useEffect } from 'react';
2
import cat from '../Category.json'
3
function AddProdocts() {
4
useEffect(() => {
5
console.log("New Category Added");
6
}, [cat]);
7
return (
8
<div className='mx-auto w-50 border p-4 rounded-4 mt-4 '>
9
<form action="">
10
<div className='mb-3 row align-self-center'>
11
<label htmlFor="price" className='form-label cols '>Category: </label>
12
<select id="" className="form-select col ms-2">
13
{cat.map((value, i) => <option key={i}>{value}</option>)}
14
</select>
15
<button type='button' className='btn btn-success col-auto text-center' onClick={() => {
16
let newCategory = prompt("Please enter your new Category");
17
newCategory && //check if newCategory isnt empty
18
cat.push(newCategory) // push data inside your json file
19
}}>+</button>
20
</div>
21
<button type="submit" className='btn btn-primary'>Submit</button>
22
</form>
23
</div>
24
);
25
}
26
i want to update option with new item added in this part of code
JavaScript
1
4
1
<select id="" className="form-select col ms-2">
2
{cat.map((value, i) => <option key={i}>{value}</option>)}
3
</select>
4
Advertisement
Answer
If you want React re-render your component when new category added, add local state to it. Here is the updated code:
JavaScript
1
27
27
1
import React, { useEffect } from 'react';
2
import cat from '../Category.json'
3
function AddProdocts() {
4
// New code
5
const [categories, setCategories] = useState(cat)
6
return (
7
<div className='mx-auto w-50 border p-4 rounded-4 mt-4 '>
8
<form action="">
9
<div className='mb-3 row align-self-center'>
10
<label htmlFor="price" className='form-label cols '>Category: </label>
11
<select id="" className="form-select col ms-2">
12
{categories.map((value, i) => <option key={i}>{value}</option>)}
13
</select>
14
<button type='button' className='btn btn-success col-auto text-center' onClick={() => {
15
let newCategory = prompt("Please enter your new Category");
16
// New code
17
if(newCategory) {
18
setCategories(prev => [prev, newCategory])
19
}
20
}}>+</button>
21
</div>
22
<button type="submit" className='btn btn-primary'>Submit</button>
23
</form>
24
</div>
25
);
26
}
27