0

Im switching classes and text with React Aria this way ->

const [toggle, setToggle] = useState(false);
const toggler = () => {
 toggle ? setToggle(false) : setToggle(true);
};

{toggle ? "Off" : "On"}{state.isSelected ? "Off" : "On"}

The additional state.isSelected is a preset React Aria state that I also want to use... This works so i can toggle the element with the mouse and the keyboard, but obviously now I have double the text... How could i combine "toggle" and "state.isSelected" into one command / line?

Something like =>

{toggle ? state.isSelected ? "Off" : "On"}

which obviously doesn't work.

Id also like to toggle my classes this way =>

${toggle ? OR state.isSelected ? styles.ToggleActiveOff : styles.ToggleActiveOff}

So, if i toggle with the mouse Or if i toggle with the spacebar, change class / text

mike
  • 749
  • 2
  • 13
  • 24
  • Looks like I can take out my "toggle" completely and "state.isSelected" will handle all events for me... although, it would be cool to know how to do what I originally needed for the future... have something like State and/or anotherState ? "on" : "off" – mike Sep 14 '22 at 22:46

1 Answers1

0

Yeah, the premise is an odd on with button element since by default it supports focus and pressing with the keyboard. So even a regular button's onClick will trigger on focus and keyboard Enter by default. Also, even if you did need to control button state via two distinct user actions, you'd still want both actions wired up to the same state. So, I don't think this is ever something you'd want to do.

But to your second question, to conditionally apply classes, you can use a plain old ternary for basic if/else conditions. For other scenarios, you can use a helper function or library like clsx or use string interpolation.

Threw up a very contrived example up for illustration. Don't really need react-aria toggle button here to demonstrate conditional class names, but this evolved from your original question and I'd happened to be using it already for something else. You could make the expressions more complex with whatever logical operators or multiple conditions as needed.

Example/Demo

https://codesandbox.io/s/aria-multiple-toggle-state-conditional-classes-3ugx77

abgregs
  • 1,170
  • 1
  • 9
  • 17