Search code examples
javascriptcssreactjsreact-spring

How to change icons with React Spring?


I want to change the icon when I click on it with react spring. For example, when I click on "🤪", it will change into "😄". In the documentation of react spring, it's possible to make it with the transition props, but how do I toggle it with onClick?

https://www.react-spring.io/docs/props/transition

the following codes are provided by react spring

<Transition
  items={toggle}
  from={{ position: 'absolute', opacity: 0 }}
  enter={{ opacity: 1 }}
  leave={{ opacity: 0 }}>
  {toggle =>
    toggle
      ? props => <div style={props}>😄</div>
      : props => <div style={props}>🤪</div>
  }
</Transition>

Solution

  • create a button and change toggle value on click:

    function App() {
      const [toggle, setToggle] = React.useState(false);
      return (
        <>
          <button onClick={() => setToggle(!toggle)}>toggle</button>
          <Transition
            items={toggle}
            from={{ position: "absolute", opacity: 0 }}
            enter={{ opacity: 1 }}
            leave={{ opacity: 0 }}
          >
            {toggle =>
              toggle
                ? props => <div style={props}>😄</div>
                : props => <div style={props}>🤪</div>
            }
          </Transition>
        </>
      );
    }