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.
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/