Home > other >  Change dropdown options style onClick
Change dropdown options style onClick

Time:09-28

So I'm having dropdown with few options. I want to change its classes dynamically, so after I click at e.g. second option, I want its class to change so I could style selected option.

For now it changes class but of all elements. I want to change class of only one clicked element. And if I click on another one, previous class goes back to beginning class. What am I doing wrong here? Thanks.

  const [optionStyle, setOptionStyle] = useState<boolean>(false);

  const onOptionClickHandler = (action: any) => {
    action();
    close();
  };

  const getActiveElement = () => {
    const element = selectedIndex.length > 1 ? getActiveOption(list, 0) : null;
    const active = element ? element.id : -1;

    return selectedIndex.length > 1
      ? active
      : list[activeElement]
        ? list[activeElement].id
        : -1;
  };

    {list.map((options: any) => (
      <div onClick={() => setOptionStyle(options.id)} className={optionStyle ? 'colored' : 'not_colored'}>
          <DropdownOptions
            key={options.id}
            option={options}
            onOptionClick={onOptionClickHandler}
            activeId={getActiveElement()}
        />
      </div>
    ))}

CodePudding user response:

In optionStyle you pass the ID. In this case, you just need to compare the ID of the item with the ID that is currently activated

const [optionStyle, setOptionStyle] = useState<boolean | string>(false);

const onOptionClickHandler = (action: any) => {
    action();
    close();
};

const getActiveElement = () => {
    const element = selectedIndex.length > 1 ? getActiveOption(list, 0) : null;
    const active = element ? element.id : -1;

    return selectedIndex.length > 1
        ? active
        : list[activeElement]
            ? list[activeElement].id
            : -1;
};

return (
    <>
        {list.map((options: any) => (
            <div onClick={() => setOptionStyle(options.id.toString())} className={optionStyle === options.id ? 'colored' : 'not_colored'}>
              <DropdownOptions
                key={options.id}
                option={options}
                onOptionClick={onOptionClickHandler}
                activeId={getActiveElement()}
            />
            </div>
        ))} 
    </>
);
  • Related