skip to Main Content

I have a collection of div that I would like to add/remove a style to with an onClick event.

enter image description here

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


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

    const Parent = () => {
      const [selectedId, setSelectedId] = useState(null)
      return ids.map(id => <Badge selected={id === selectedId} onClick={() => setSelectedId(id)} id={id} />)
    }
    
    const Badge = (props) => {
      return <Button onClick={props.onClick} style={props.selected ? selectedStyle : unselectedStyle}>{props.id}</Button>
    }
    

    If a state has to be shared across multiple components, then put it on higher component.

    Login or Signup to reply.
  2. 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

    const [activeDiv,setActiveDiv]=useState(null)
    const divs = [{value:6.5,index:6.5},{value:5.5,index:5.5},{value:4.5,index:4.5}]
    
    return ({divs.map(div=>{
      return (
       <div style={activeDiv===div.index&& {backgroudColor:"blue"}}
        onClick={e=>{setActiveDiv(div.index)}}> {div.value} </div>)
        })})
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search