Search code examples
javascriptreactjsnext.jsweb-componentstyled-jsx

How to apply parent styled jsx to children?


How can I apply parent styled JSX to child components? My JSX styles are being applied to the parent button element below (as it has its own JSX class), but not to its children.

Here's the code for the parent button element:

export function LoginButton({children, className, ...props}){
        return (
            <>
                <style jsx>
                    {`
                        .loginButton {
                            padding: .75rem 2rem;
                            width: 100%;
                            border-radius: 2rem;
                            background: var(--primary);
                            color: var(--back); 
                            font-size: 2rem !important;
    
                        }
    
                        .loginButton:hover i {
                            transform: translateX(.5rem);
                        }
    
    
                    `}
                </style>
                <button className={`loginButton ${className}`} {...props}>
                    {children}
                </button>
            </>
        )
}

Here's an example of how I'm using this code:

<LoginButton className="flex center gap1">
    <h3>Sign in</h3>
    <i className="bx bxs-right-arrow-alt"></i>
</LoginButton>

The <i> element is not getting the JSX styles for the button. I've tried cloning the elements and updating JSX to global but neither worked.

How can I apply the JSX styles to the component's children?


Solution

  • From this nextjs blog post

    The styles that we add to a component using affect only the elements inside that component, but not child components.

    In your example, .loginButton styles works correctly, however .loginButton:hover i won't be applied because there is no i element in your component code :

    <button className={`loginButton ${className}`} {...props}>
      {children}
    </button>
    

    At times, we may need to override a certain style of a child component. To do this, Styled JSX provides :global(), giving access to one-off global selectors.

    You can use :global(i) to style the children elements :

    .loginButton:hover :global(i) {
      transform: translateX(.5rem);
    }