Home > Mobile >  How to convert an array of string integers to an array of number integers
How to convert an array of string integers to an array of number integers

Time:05-04

Essentially I have a select dropdown that is being populated by an API.

If you look at the following code snippet, I essentially created an array of IDs called "first" and made it the value for the first select option above the map that I've done to populate the rest of the select.

Now in my handleChange when I log the value of a selected option it returns the value of the given option in an array of string numbers.

--> Example... if user selects the second option ['1']

When the user selects 'All IDs' that's where the issue is. When that option is selected whats logged is ---> ['1,2,6,8,15,16,17,20,22,23,24,25,26,27,30,32,33,34,36']

I understand that I could use the split method but it crashes for any other option that's selected.

How could I get around that?

const DropDown = ({ list = [], title, onChange }) => {
  const handleChange = (e) => {
    const { value } = e.target
    const arr = [value]
    console.log(arr)
    // onChange(Number(value))
  }

  const first = list.map((list) => list.id)

  return (
    <>
      <select onChange={handleChange}>
        <option value={first}>{title}</option>
        {list.map((item) => (
          <option key={item.id} value={item.id}>
            {item.name}
          </option>
        ))}
      </select>
    </>
  )
}

CodePudding user response:

e.target.value is a string, so you'll need to change this:

const arr = [value]

to

const arr = value.split(",").map(Number);

CodePudding user response:

You can use whatever you want as the value (key) of the "All" option. For example, in the following, I've used "all" as the key and handled that specifically in the handleChange handler.

const DropDown = ({ list = [], title, onChange }) => {
  const handleChange = (e) => {
    const { value } = e.target;

    if (value === "all") {
      onChange(list.map((l) => l.id));
    } else {
      onChange([parseInt(value, 10)]);
    }
  };

  return (
    <>
      <select onChange={handleChange}>
        <option value="all">{title}</option>
        {list.map((item) => (
          <option key={item.id} value={item.id}>
            {item.name}
          </option>
        ))}
      </select>
    </>
  );
};

You can use value.split(",") as well, which would work for your specific example but would not be sufficient if you need to handle different types of items in the list (perhaps strings that could contain their own ,s).

Here's the above code in action

  • Related