0

I am trying to display the values of an array in <option> tag in react js. So far I have failed.

<select>
  {
    op.map(value => (<option key={value} value={value}>{value}</option>))
  }
</select>

op is an array. op = 1,2,3. I got the array op like this:

for (let i=0; i<Math.ceil(response.data.length/end); i++) {
   op[i] = i+1;
}

When I inspect is see only this:

<select></select>
2
  • the code shown looks ok. you might need to check other things like, does the op contains some calls. or show more code to debug Commented Aug 20, 2021 at 11:04
  • Could you print op array after the for loop to check if it has values indeed? Commented Aug 20, 2021 at 11:05

1 Answer 1

1

Please check the (select) example

Math.ceil(response.data.length/end); needs to be replaced according to your needs.

If you need to make an ajax call do it like:

import { useEffect, useState } from "react";
import "./styles.css";

export default function App() {
  const [selOption, setSelOption] = useState(1);

  const [op, setOptions] = useState([]);

  useEffect(() => {
    //make ajax call here.

    //set this on success of the ajax call
    /*axios.get().then(()=>{
         /here.
    }) 
    */
    let o = [];
    for (let i = 0; i < 5; i++) {
      o[i] = i + 1;
    }
    setOptions(o);
  }, []);

  return (
    <div className="App">
      <select
        value={selOption}
        onChange={(e) => {
          setSelOption(e.target.value);
        }}
      >
        {op.map((value) => (
          <option key={value} value={value}>
            {value}
          </option>
        ))}
      </select>
      Selected:{selOption}
    </div>
  );
}

Simple snippet for demo

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [selOption, setSelOption] = useState(1);

  let op = [];
  for (let i = 0; i < 5; i++) {
    op[i] = i + 1;
  }

  return (
    <div className="App"><select
        value={selOption}
        onChange={(e) => {
          setSelOption(e.target.value);
        }}
      >
        {op.map((value) => (
          <option key={value} value={value}>
            {value}
          </option>
        ))}
      </select>
      Selected:{selOption}
    </div>
  );
}

Sign up to request clarification or add additional context in comments.

Comments

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.