cssreactjsmaterial-uimakestyles

Add and remove classes in React


How can I add/ remove a className on click to change the style of some component?

enter image description here


Solution

  • const [isRotated, setIsRotated] = useState(false);
    
    handleClick() {
     setIsRotated(true)
    }
    
    <button className={isRotated && 'rotate-class'} onClick={handleClick} />
    { !isRotated && <Element/>} // this will hide the element when clicked on the button
    

    This would a better approach then setting display: none on the other elements, but if you must do that, do this:

     <Element style={{ display: isRotated ? 'none': 'block' }} /> // I'm guessing the default style of display is 'block' of the elements you want to hide