Aejg
Aejg

Reputation: 81

React - rotate chevron on click

I am trying to rotate a chevron when clicking it by using state to toggle a className, but I can't get it to work. The component looks like this:

import React, { useState } from 'react';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

const FilterGroup = () => {
    const [rotateChevron, setRotateChevron] = useState(false);

    const handleRotate = () => setRotateChevron(!rotateChevron);

    return (
             <ExpandMoreIcon className={"filters__chevron " + rotateChevron ? "rotate" : null} onClick={handleRotate} />
           )
    }

export default FilterGroup;

This is the CSS :

.filters__chevron {
    border-radius: 2px;
    transition: all 2 linear;
}

.filters__chevron.rotate {
    transform:rotate(180deg);
}

Any help appreciated. Thanks!

Upvotes: 0

Views: 9001

Answers (2)

Aejg
Aejg

Reputation: 81

import React, { useState } from 'react';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

const FilterGroup = () => {
    const [rotateChevron, setRotateChevron] = useState(false);

    const handleRotate = () => setRotateChevron(!rotateChevron);

    const rotate = rotateChevron ? "rotate(180deg)" : "rotate(0)"

    return (
             <ExpandMoreIcon style={{ transform: rotate, transition: "all 0.2s linear" }} onClick={handleRotate} />
      )
}

export default FilterGroup;

Upvotes: 3

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

Try this:

className={`filters__chevron ${rotateChevron ? "rotate" :''}`}

Upvotes: 1

Related Questions