2
votes

I'm still learning the interactions between antdesign and styled-components, and I have a question:

I know I'm able to pass the styles for components like the popover (which accepts the "overlayClassName" prop) doing something like this:

const styledPopover = ({ className, ...props }) => (<ANTPopover {...props} overlayClassName={className} />);
styledPopover.propTypes = {
   className: PropTypes.string,
};
export const Popover = styled(styledPopover)`...`

But for the notifications, I have the className prop, but there's no component to style, just a function.

https://ant.design/components/notification/

Is there a way to wrap it into a styled component?

Thanks a lot,

1
I managed to make it work the way I wanted through the "createGlobalStyle" method in the styled-components API. But I'm not happy with this. :) - Raphael Aleixo

1 Answers

0
votes

An easy way to style the Antd Notification is using the style config from the API

style: Customized inline style -> CSSProperties

Here is an simple example CodeSandBox.


To use antd together with styledComponents you can override getContainer which returns by default document.body. Thats why your createGlobalStyle approach works.

Here you can return a ref to your trigger e.g. to a Button.

getContainer: (triggerNode) => buttonRef.current

Note: With this the correct style is choosen, but the whole Notification seems to be broken (test the cancel button).

Full code example from CodeSandbox.

import React, { useRef } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Button, notification } from "antd";
import styled from "styled-components";

const Styled = styled.div`
  .ant-notification-notice {
    background-color: green;
  }
`;

const Notification = () => {
  const openNotification = () => {
    notification.open({
      message: "Notification Title",
      duration: 20,
      description:
        "This is the content of the notification. This is the content of the notification. This is the content of the notification.",
      onClick: () => {
        console.log("Notification Clicked!");
      },
      getContainer: (triggerNode) => {
        console.log(triggerNode);
        console.log(buttonRef);
        // return document.body;
        return buttonRef.current;
      }
    });
  };

  const buttonRef = useRef(null);

  return (
    <Styled>
      <Button type="primary" onClick={openNotification} ref={buttonRef}>
        Open the notification box
      </Button>
    </Styled>
  );
};

ReactDOM.render(<Notification />, document.getElementById("container"));