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

119
Visualizações
React single selectable component

I'm new to react and I'm trying to make a selection button where only a single item can be selected and it deselects the other items. I have made it as far as selecting an item, but not the deselecting the other items part.

Below is my component code :

class Diamond extends React.Component {
  constructor(props) {
    super(props);
    this.selectDiamond = this.selectDiamond.bind(this);
    this.state = {selected : false};
  }

  selectDiamond() {
    this.setState( {selected : true} );
  }

  render() {
    if (this.state.selected == true) {
      return (
        <div onClick={this.selectDiamond} className="diamond-selected hover:scale-[105%] duration-300 ">{this.props.text}</div>
      )
    } else {
      return(
        <div onClick={this.selectDiamond} className="diamond-unselected hover:scale-[105%] duration-300 ">{this.props.text}</div>
      )
    }
  }
}

and this is how I render it :

<div>
    {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond key={i} text={item}/>
        )
    )}
</div>

I know I need a reference to the <Diamond/>s so I tried something like :

let diamonds = [];

//and on the constructor method of the component 
constructor(props) {
   super(props);
   diamonds.push(this);
}

but for some reason when I call diamonds.length it gives me double the number of the created items, and I also do not know what to do from there. I also would like the first item to be selected by default.

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

0

I would reccomend using hooks instead of class components. Here is snippet how it can be done:

const Diamond = ({ text, setSelected, isSelected }) => {
  return (
    <div
      onClick={setSelected}
      className={`diamond-${
        isSelected ? "" : "un"
      }selected hover:scale-[105%] duration-300`}
    >
      {text}
    </div>
  );
};

const ListDiamonds = () => {
  const [selectedIdx, setSelectedIdx] = useState(null);

  return (
    <div>
      {["BOY", "GIRL", "BAKLA", "TOMBOY"].map((item, i) => (
        <Diamond
          key={i}
          text={item}
          isSelected={selectedIdx === i}
          setSelected={() => setSelectedIdx(i)}
        />
      ))}
    </div>
  );
};

I did not test it but in general concept it like that.

Also do not push this from constructor, it is bad practice. You could read rect lifting state up: https://reactjs.org/docs/lifting-state-up.html or better with hooks: https://www.freecodecamp.org/news/what-is-lifting-state-up-in-react/

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