react tailwind button that flips over and inverts colors when hovered in typescript

Here's how you can create a button using TailwindCSS and React and invert its colors when hovered using TypeScript:

import React, { useState } from "react";
import tw from "tailwind-styled-components";

const InvertOnHoverButton = tw.button`bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded`;

interface Props {
  onClick: () => void;
  text: string;
}

const AppButton: React.FC<Props> = ({ onClick, text }) => {
  const [isHovered, setIsHovered] = useState(false);

  const handleHover = () => {
    setIsHovered(!isHovered);
  };

  return (
    <InvertOnHoverButton
      onClick={onClick}
      onMouseEnter={handleHover}
      onMouseLeave={handleHover}
      css={`
        ${isHovered && "bg-white text-blue-500 hover:bg-blue-500 hover:text-white"}
      `}
    >
      {text}
    </InvertOnHoverButton>
  );
};

export default AppButton;
750 chars
33 lines

In this example, we have created a button with bg-blue-500 background color and text-white text color using the TailwindCSS library. We add the hover:bg-blue-700 property to change the background color on hover.

We then create a new component called InvertOnHoverButton that takes the button as a base and changes the background color on hover by applying bg-white text-blue-500 hover:bg-blue-500 hover:text-white.

In the main AppButton component, we use the useState hook to create a isHovered state variable, and toggle it using the handleHover function on the onMouseEnter and onMouseLeave events.

Finally, we apply the isHovered state variable's value to the component styles using the css prop, by applying styles dynamically when isHovered is true.

This way, the background color changes to white and text color changes to blue when the button is hovered.

gistlibby LogSnag