Trying to create a select element using database values in a react-redux app

Viewed 29

I'm returning a set of text values from a database table and then trying to create a select element from them. I get the following error msg:

  • Warning: Each child in a list should have a unique "key" prop.

I create a local store with the values in an array titled categories:

let categoriesFromApi = fetchedCategories.map(category => {
    return { key: category, value: category, display: category }
})
this.setState({ categories: [{ key: 0, value: '', display: '(Select A Category)' }].concat(categoriesFromApi) });

and then I build the select element:

<select value="Select a Category"
    onChange={(e) => this.setState({ selectedCategory: e.target.value, validationError: e.target.value === "" ? "You must select a Category" : "" })}>
    {this.state.categories.map((category) => <option value={category.category}>{category.category}</option>)}
</select>

What else do I need to do?

2 Answers

Try

<select
    value="Select a Category"
    onChange={e =>
        this.setState({
            selectedCategory: e.target.value,
            validationError:
                e.target.value === "" ? "You must select a Category" : ""
        })
    }
>
    {this.state.categories.map((category, idx) => (
        <option key={`${category.id}-${idx}`} value={category.category}>
            {category.category}
        </option>
    ))}
</select>;

wasn't selecting the right items from the category:

simplified the assignment:

this.setState({ categories: fetchedCategories });

then:

<select value="Select a Category"
    onChange={(e) => this.setState({ selectedCategory: e.target.value, validationError: e.target.value === "" ? "You must select a Category" : "" })}>
    {this.state.categories.map((category) => <option value={category.cat_item}>{category.cat_item}</option>)}
</select>
Related