Search code examples
reactjsantdstyled-components

How to Customize wrapped Antd Button with Styled-Components?


I'm having a lot of difficult to target a component wrapping an antd button. All I want to do is to modify the <button> tag to have width: 100%, but I need to do it from outside of the component. Here is what I have:

LogoutButton.js

import { useAuth0 } from "@auth0/auth0-react";
import { clearSessionCookie } from 'sessions';
import { Button } from 'antd';


function LogoutButton () {
  const { logout } = useAuth0();

  const handleLogout = () => {
    clearSessionCookie();
    return logout({ returnTo: process.env.REACT_APP_AUTH_LOGOUT_REDIRECT_URI });
  }

  return (
    <Button danger type="primary" onClick={handleLogout}>
      Log Out
    </Button>
  );
};

export default LogoutButton;

HomePage.js

import { LogoutButton } from 'components';
import { Menu } from 'antd';
import { UserOutlined, VideoCameraOutlined } from '@ant-design/icons';
import styled from 'styled-components';

const ButtonContainer = styled.li`
    padding: 0 16px;
`;

const StyledLogoutButton = styled(LogoutButton)`
    width: 100%;
    background-color: green;
`;

function HomePage() {

    return (
        <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
            <Menu.Item key="1" icon={<UserOutlined />}>
                nav 1
            </Menu.Item>
            <Menu.Item key="2" icon={<VideoCameraOutlined />}>
                nav 2
            </Menu.Item>
            <ButtonContainer>
                <StyledLogoutButton />
            </ButtonContainer>
        </Menu>
    );
}

export default HomePage;

The problem:

To modify StyledLogoutButton in HomePage.js in order to correctly set LogoutButton width to 100%. I've tried &, &&&, using a custom class... nothing seems to work. I can't target the <button> html tag.

Any help is much appreciated.


Solution

  • <LogoutButton width="auto" />
    
    
    function LogoutButton ({width}) {
      const { logout } = useAuth0();
    
      const handleLogout = () => {
        clearSessionCookie();
        return logout({ returnTo: process.env.REACT_APP_AUTH_LOGOUT_REDIRECT_URI });
      }
    
      return (
        <Button width={width} danger type="primary" onClick={handleLogout}>
          Log Out
        </Button>
      );
    };
    
    const Button = styled.button`
        width: ${({width}) => width ? width : 'auto'}
    `;