I have a collection of div
that I would like to add/remove a style to with an onClick
event.
I am able to add the style, but what I need to have is only one div selected at a time. The code below, when I click the div
it adds it as a selection but when I click another, it adds it as a second selection. What I need to happen is when a div is selected, the previous div is reverted back to "normal".
export default function SearchFilterAttributeBadge(props: {attribute: SearchFilterAtttribute, category: string, clickHandler: (event: React.MouseEvent<HTMLAnchorElement>) => void}) {
const [selectedSize, setSelectedSize] = useState<string>("");
function highlightSelected(id: string) {
setSelectedSize(id);
}
return (
<>
<div className="col">
<a className={`badge size-badge ${selectedSize === props.attribute.id.toString() ? "selected-size" : ""}`} data-id={props.attribute.id.toString()} data-name={props.category} data-value={props.attribute.name} onClick={(e) => {props.clickHandler(e); highlightSelected(props.attribute.id.toString())}}>{props.attribute.name}</a>
</div>
</>
)
}
2
Answers
You have to keep a badge stage on parent component. Putting a state in each badge component only make you able to control a single badge’s style.
You can fix it by putting a state of selected badge in the parent component. Once you click on any badge, update a selected badge’s id. You can use the state to update a badge component afterward.
If a state has to be shared across multiple components, then put it on higher component.
since i can not see your whole code, lets assume this one and apply the concept to yours ,
make an array of objects, each object contains the value and an index for it
and by this method whenever you click on any method the active class will be toggeled to it and the previous div will be reverted back