Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda