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
Yeah, the premise is an odd on with
buttonelement since by default it supports focus and pressing with the keyboard. So even a regular button'sonClickwill trigger on focus and keyboardEnterby 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
clsxor use string interpolation.Threw up a very contrived example up for illustration. Don't really need
react-ariatoggle 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