Home > Net >  How to populate an HTML datalist from an array of JSON objects?
How to populate an HTML datalist from an array of JSON objects?

Time:03-15

I'm using React, Node, Express, Postgres. I have a component that is a datalist whose options are to be populated from a database table. My table query returns an array of json objects, and I want to iterate through this array to populate my datalist.

React Component

import React, { Fragment, useState, useEffect } from "react";

const DataList1 = () => {

    const [suppliers, setSuppliers] = useState([]);

    //Search query for list of supplier names and their ids

    const getSuppliers = async () => {
        try {
            
            const response = await fetch("http://localhost:5000/supplier");
            const jsonData = await response.json();            

            setSuppliers(jsonData);
            console.log(jsonData);

        } catch (err) {
            console.log(err.message);
        }
    }

    useEffect(() => {
        getSuppliers();
    }, []);

    return <Fragment>
        <button  className="btn btn-danger" onClick={getSuppliers}></button>

        <label htmlFor="SupplierDatalist">Choose a supplier:</label>
        <input list="SupplierDatalist" id="SupplierDatalist"/>

        <datalist id="SupplierDatalist">
            {suppliers.map(suppliers => (
                <option key={suppliers.supplier_id} value={suppliers.supplier_name} />
            ))}
        </datalist>    
    </Fragment>
}

export default DataList1;

And this is how my array looks as an example:

Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
​
0: Object { supplier_id: "2", supplier_name: "Sup1" }
​
1: Object { supplier_id: "3", supplier_name: "Sup2" }
​
2: Object { supplier_id: "4", supplier_name: "Sup3" }
​
...

To add a little context what I'm trying to do here, each datalist selection will need to take as parameter either the id/name to update some other selection

CodePudding user response:

You can map through the array and create option for datalist.

<datalist id="SupplierDatalist">
  {suppliers.map(supplier => (
    <option key={supplier.supplier_id} value={supplier.supplier_name} />
  ))}
</datalist>

CodePudding user response:

So moving my datalist stuff into form tag solved my problem, though I have no idea why

  • Related