To add an icon on hover for the ChakraUI Button
component using a custom theme, you can leverage ChakraUI's theme customization capabilities. By modifying the theme, you can customize the button's styles to display an icon on hover. Here's how you can achieve this:
- Install ChakraUI (if you haven't already):
bashnpm install @chakra-ui/react @emotion/react @emotion/styled framer-motion
- Create a custom theme for the button:
jsx// customTheme.js
import { extendTheme } from '@chakra-ui/react';
const customTheme = extendTheme({
components: {
Button: {
baseStyle: {
_hover: {
// Customize the icon appearance on hover
// Adjust the icon and styles as per your requirement
// Here, I'm using the 'AddIcon' from ChakraUI as an example
'& > svg': {
display: 'inline-block', // Show the icon on hover
},
},
},
},
},
});
export default customTheme;
- Wrap your application with the custom theme:
jsx// index.js (or your main entry file)
import React from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import customTheme from './customTheme';
import App from './App';
const RootApp = () => (
<ChakraProvider theme={customTheme}>
<App />
</ChakraProvider>
);
export default RootApp;
- Use the
Button
component with an icon:
jsximport React from 'react';
import { Button } from '@chakra-ui/react';
import { AddIcon } from '@chakra-ui/icons';
const MyButton = () => {
return (
<Button leftIcon={<AddIcon />} colorScheme="teal">
Click Me
</Button>
);
};
export default MyButton;
Now, when you hover over the button, the icon (in this case, AddIcon
) will be displayed on the left side of the button text. You can adjust the icon appearance and styles based on your specific requirements.
By using ChakraUI's custom theme, you can easily customize the button's styles to add an icon on hover. This approach allows you to maintain a consistent design across your application while adding interactive elements like hover effects.