Search code examples
javascriptreactjsmap-function

How to access datavalues using Map Function?


I have a "data" state which stores the values taken from my database.

const [data, setData] = useState([]);

"data" contains an array of objects which was extracted from my database.

// so data is essentially (if I console.log it): 
data = [
{student:"Jeff",country:"London"}, 
{student:"Benjamin",country:"France"},
{student:"Franklin",country:"USA"}
];

I am using React Select to display the labels of this data (I only want "student" data) but I am not sure how to map this data into values and labels to put them as options in my React Select component. I have tried the following but it gives me an error.

import Select from "react-select";
function myTable() {
   const myOptions = data.map(info => {
       value: {info.student},
       label: {info.student}
   });

   return (
     <tr>
        <td>
            <Select isMulti options={myOptions}></Select>
        </td>
     </tr>
   )
};

I want my options to contain values and labels from my data state object.


Solution

  • You don't need to add the info.student in an object.

    import Select from "react-select";
    function myTable() {
       const myOptions = data.map(info => ({
           value: info.student,
           label: info.student
       }));
    
       return (
         <tr>
            <td>
                <Select isMulti options={myOptions}></Select>
            </td>
         </tr>
       )
    

    Codesandbox example