'Styled Components: How can I rotate an svg icon on click?

const IconButtonWrapper = styled((props: IconWrapperProps) => {
    return <IconButton {...props} />;
})`
    float: right;
    transform: rotate(0deg);
    overflow: hidden;
    transition: all 0.3s ease-out;
    ${(props) =>
        props.rotate &&
        css`
            transform: rotate(180deg);
        `};
`;

Right now, I'm trying it with this and it's not quite correct. I currently have props.rotate as a boolean setup with a click handler to rotate if on click. What should I do?



Solution 1:[1]

It's unclear from your example how you pass "rotate" prop down to styled component, so I did a little refactoring on your code and added a container component to hold rotation state: https://codesandbox.io/s/wyx6pqj13w

Hope this helps!

Code in the link is shown here

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';
import './styles.css';

const IconButton = () => <button>Icon</button>;

const IconButtonWrapper = styled.div`
  float: right;
  transform: rotate(0deg);
  overflow: hidden;
  transition: all 0.3s ease-out;
  transform: ${(props) => (props.rotate ? `rotate(180deg)` : '')};
`;

class IconButtonContainer extends Component {
  state = {
    rotate: false,
  };

  handleClick = () =>
    this.setState(
      (prevState) => ({ rotate: !prevState.rotate }),
      () => console.log(this.state.rotate)
    );

  render() {
    return (
      <IconButtonWrapper rotate={this.state.rotate} onClick={this.handleClick}>
        <IconButton />
      </IconButtonWrapper>
    );
  }
}

const App = () => {
  return (
    <div className="App">
      <IconButtonContainer />
    </div>
  );
};

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GollyJer