Home > Blockchain >  Update Select When New Category Added
Update Select When New Category Added

Time:10-09

hi guys i want to update select options when user add new category can anyone tell me how to do this ?

import React, { useEffect } from 'react';
import cat from '../Category.json'
function AddProdocts() {
    useEffect(() => {
        console.log("New Category Added");
    }, [cat]);
    return (
        <div className='mx-auto w-50 border  p-4 rounded-4 mt-4 '>
            <form action="">
                <div className='mb-3 row align-self-center'>
                    <label htmlFor="price" className='form-label cols '>Category: </label>
                    <select id="" className="form-select col ms-2">
                        {cat.map((value, i) => <option key={i}>{value}</option>)}
                    </select>
                    <button type='button' className='btn btn-success col-auto text-center' onClick={() => {
                        let newCategory = prompt("Please enter your new Category");
                        newCategory && //check if newCategory isnt empty
                            cat.push(newCategory) // push data inside your json file 
                    }}> </button>
                </div>
                <button type="submit" className='btn btn-primary'>Submit</button>
            </form>
        </div>
    );
}

i want to update option with new item added in this part of code

<select id="" className="form-select col ms-2">
{cat.map((value, i) => <option key={i}>{value}</option>)}
</select>

CodePudding user response:

If you want React re-render your component when new category added, add local state to it. Here is the updated code:

import React, { useEffect } from 'react';
import cat from '../Category.json'
function AddProdocts() {
    // New code
    const [categories, setCategories] = useState(cat)
    return (
        <div className='mx-auto w-50 border  p-4 rounded-4 mt-4 '>
            <form action="">
                <div className='mb-3 row align-self-center'>
                    <label htmlFor="price" className='form-label cols '>Category: </label>
                    <select id="" className="form-select col ms-2">
                        {categories.map((value, i) => <option key={i}>{value}</option>)}
                    </select>
                    <button type='button' className='btn btn-success col-auto text-center' onClick={() => {
                   let newCategory = prompt("Please enter your new Category");
                    // New code
                    if(newCategory) {
                      setCategories(prev => [...prev, newCategory])
                     }
                    }}> </button>
                </div>
                <button type="submit" className='btn btn-primary'>Submit</button>
            </form>
        </div>
    );
}
  • Related