Search code examples
javascriptreactjsexpress

How to populate countryList data in Form.Select in react js


I have a data file that contains a list of all countries and I want these countries to populate in a select input similar to what we see on popular websites when a user logs in and visits his profile page to edit his information such as name, address and country.

but when I run my code it doesn't seem to populate anything.

what am I doing wrong?

here is my code:

data.js

export const countryList = [
    "Afghanistan",
    "Albania",
    "Algeria",
    "American Samoa",
    "Andorra",
    "Angola",
    "Anguilla",
    "Antarctica",....,....,.....]

profile.js:

    import { countryList, documentList,shipmentPurposeList } from "../LocalData/data"
    import React, {Component, useState, useEffect} from 'react';
      const [country,setCountry] = useState([]);
    
      useEffect(() => {
            Axios.get('http://localhost:3001/login').then((response) => {
    
                if(response.data.loggedIn == true){
            
                 setCountry(countryList);
                }
            });
        },[]);


     return (

      <Row>
                      <Col md={11}>
                          <Form.Group controlId="exampleForm.ControlInput1"> 
                          <Form.Label className={'font-12 mt-3 color-gray inputLabel'}>Country</Form.Label>
                            <Form.Select aria-label="Select Title">

                                  { country.map((item, i) => {
                                                 
                                     <option key={i} value={item}>
                                      {item}
                                      </option>
                                     
                                     })
                                   }
                                  </Form.Select>
                                 </Form.Group>
                             </Col>
                          </Row>
)

Solution

  • You have a syntax "error", your map callback function doesn't return the JSX element, it just defines it

    It should be

    { country.map((item, i) => (
                                                     
                                         <option key={i} value={item}>
                                          {item}
                                          </option>
                                         
                                         ))
                                       }
    

    Notice the round brackets after the arrow, instead of curly braces. Round brackets meaning you want to return whatever's in there, whilst curly braces define the body of the function.