reactjsreact-datepickerchakra-ui

How to apply chakra-ui styles to custom components? (react-datepicker)


I'd like to define styles for my Datepicker component through the Chakra-ui styles.

import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { chakra } from '@chakra-ui/react';
const StyledDatepicker = chakra(DatePicker);

I've used the chakra factory function to be able to give the StyledDatepicker some styles through props, as shown in the code above, but I'd like to define everything in a separate styles .ts file like I've done for the built-in chakra components.

I've made a Datepicker.ts file with some style definitions and added it to the overrides object which is exported here as styles:

const styles = extendTheme(overrides);
export { styles };

which is imported in App.tsx and assigned to the theme prop of my ChakraProvider.

I've made some custom components which was fine, though not exactly what I'm looking for, and I'm looking to change the styles of the header container, the element with classname react-datepicker__header - no examples of making a custom component for this on react-datepicker website. I know I can do it with CSS files, but I'd really like to do all of it in the styles file for consistency.


Solution

  • The answer turned out to be fairly straightforward, but imo, chakra could have made it a bit easier to learn about this possibility. To target a css class, you just add the classname into your styles object like this:

    const DatepickerStyles = {
        baseStyle: {
            color: 'black',
            '.react-datepicker__header': {
                background: 'white',
            },
        },
    };
    

    Then do something like this where you want to use the component (In my case, the datepicker, but this will work for any component):

    function MyDatePickerComponent(props) {
    
        const datepickerStyles = useStyleConfig('Datepicker');
    
        return (
                <Datepicker
                    __css={datepickerStyles}
                    //some required props omitted for simplicity
                />
        );
    }
    

    You can use sx instead of __css, I use __css for readability. For react-datepicker and my case of styling the header specifically, I had to use a custom calendarContainer component, where I also applied the style in a similar manner by using useMultiStyleConfig instead of useStyleConfig. Hope this can be of help to someone.