Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
Create a select in react js

I created a select using react js.

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

const options = [
  {
    id: "test1",
    label: "label1"
  },
  {
    id: "test1",
    label: "label2"
  },
  {
    id: "color",
    label: "Test"
  }
];

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = (e) => {
    setValue(e.target.value);
  };
  return (
    <div className="App">
      <select value={value} onChange={handleChange}>
        {options.map((i) => {
          return <option value={i.id}>{i.label}</option>;
        })}
      </select>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I have a situation where the value (ID) is the same but the title is different like in the case with 2 first options.

Trying to click on label2 the selected arrow still selected on the previous (label1). How to fix this?
demo: https://codesandbox.io/s/red-microservice-tesgs?file=/src/App.js:0-669

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming you can not change the ids (the best way is to have unique ids), you can rely on the index of your options array:

const options = [
  {
    id: "test1",
    label: "label1"
  },
  {
    id: "test1",
    label: "label2"
  },
  {
    id: "color",
    label: "Test"
  }
];

export default function App() {
  const [value, setValue] = useState({
    id: "",
    index: ""
  });

  const handleChange = (e, index) => {
    setValue({ id: e.target.value, index: index });
  };
  return (
    <div className="App">
      <select
        value={options[value.index]}
        onChange={(e, index) => handleChange(e, index)}
      >
        {options.map((i, index) => {
          return (
            <option key={index} value={i.id}>
              {i.label}
            </option>
          );
        })}
      </select>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

It looks like you need to provide a selected attribute to your <option /> element, e.g:

const [value, setValue] = useState("");

/*[...]*/

<select onChange={handleChange}>
  {options.map(({id, label}, index) => {
    return <option key={index} value={id} selected={value === id}>{label}</option>;
  })}
</select>

Also, note the key prop above, you should always have this when iterating over JSX nodes. This should be a unique value to that index, I've used the array index, but this should really be something like the ID. If you use the index, you'll introduce all sorts of odd bugs when the source data changes.

As for the duplicate id in your array, as mentioned above, this seems like a poor data structure to me, personally. I'd ensure your id is always unique.

What purpose do you have for it to be duplicate, out of interest?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda