0

I have a drop down list for all the countries in the world with their abbreviated code. Now i want to call a useState to set it and use it to insert it to my DB.

How can i do that?

here is my code:

example of the list:

export const countryList =[ 
    {name: 'Afghanistan', code: 'AF'}, 
    {name: 'Åland Islands', code: 'AX'}, 
    {name: 'Albania', code: 'AL'}, 
    {name: 'Algeria', code: 'DZ'}, 
    {name: 'American Samoa', code: 'AS'}, 
    

    const [collcountry,setCollCountry] = useState("");//this is being set
    const [collcountrycode,setCollCountryCode] = useState("");// But how can i set the 
    //country code from the title property?



 <Form.Select aria-label="Select Country"  onChange={(e)=> { setCollCountry(e.target.value) }} >
                                   <option></option>
          { countryList.map((e, key) => (
           <option  key={key} title={e.code} value={e.name}>{e.name}</option>))                                              
          }
 </Form.Select>
2
  • So you want to have e.code instead of e.target.value? Commented Sep 15, 2021 at 8:18
  • i want both @RyanLe Commented Sep 15, 2021 at 8:43

1 Answer 1

1

bellow how you can get the country code :

  const handleCollCountryChange = (e) => {
     const country = countryList.find(
       (country) => country.name === e.target.value
     );
     setCollCountry(country.name);
     setCollCountryCode(country.code);
  };


  useEffect(() => {
     console.log(collcountry);
     console.log(collcountrycode);
  }, [collcountry, collcountrycode]);

  return (
    <select
      aria-label="Select Country"
      onChange={(e) => handleCollCountryChange(e)}
    >
      {countryList.map((country, key) => (
        <option
          key={key}
          title={country.code}
          value={country.name}
          onSelect={() => console.log("select")}
        >
          {country.name}
        </option>
      ))}
    </select>
  );

for more visibility, you can change e by country :

{ countryList.map((country, key) => (
    <option  key={key} title={country.code} value={country.name}>{country.name}</option>))                                              
}
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for your answer, but still, the country code is not being set. i believe you cant access it this way "e.target.title"
You can access it with this way e.target.title
but its not being set and when i call it it shows nothing
can you add your code to a online editor, please ? I think you have a problem somwhere else
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.