Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customize antd tooltip styles using styled components

I am trying to have custom width for antd tooltip component: Link to docs

How can this be done ?

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import { Tooltip } from "antd";
import styled from "styled-components";

const Styled = styled.div`
  .ant-tooltip-inner {
    color: yellow;
    background-color: green;
    width: 800px;
  }
`;

ReactDOM.render(
  <Styled>
    <Tooltip title="prompt text">
      <span>Tooltip will show on mouse enter.</span>
    </Tooltip>
  </Styled>,
  document.getElementById("container")
);
like image 282
Ajit T Stephen Avatar asked Aug 19 '20 18:08

Ajit T Stephen


2 Answers

The antd Tooltips docs gives you a hint for your issue. The Tooltip is added as div in the body by default, in fact your custom style won't work without any adaptions. Depending on your requirements you can use

  1. GlobalStyle from Styled Components
  2. Overwrite getPopupContainer from Antd Tooltip

GlobalStyle

As one workaround you can use the globalStyle

const GlobalStyle = createGlobalStyle`
  body {
    .ant-tooltip-inner {
      color: yellow;
      background-color: green;
      width: 800px;
    }
  }
`;

ReactDOM.render(
  <Tooltip title="prompt text">
    <GlobalStyle />
    <span>Tooltip will show on mouse enter.</span>
  </Tooltip>,
  document.getElementById("container")
);

Here is a CodeSandbox for this workaround.

getPopupContainer

From the Tooltip docs for getPopupContainer

The DOM container of the tip, the default behavior is to create a div element in body

Here you can just pass the triggerNode to be the parent object and your styles are set as expected.

const Styled = styled.div`
  .ant-tooltip-inner {
    color: yellow;
    background-color: green;
    width: 800px;
  }
`;

ReactDOM.render(
  <Styled>
    <Tooltip title="prompt text" getPopupContainer={(triggerNode) => triggerNode}>
      <span>Tooltip will show on mouse enter.</span>
    </Tooltip>
  </Styled>,
  document.getElementById("container")
);

Working CodeSandBox for using getPopupContainer.

like image 92
zerocewl Avatar answered Oct 18 '22 00:10

zerocewl


The default behavior for DOM container of the tip is to create a div element in body. You can change it to create inside Tooltip element with getPopupContainer:

<Tooltip
   getPopupContainer={(trigger) => {
      console.log(trigger);
      return trigger;
   }}
   title="prompt text"
>

With the code above you style .ant-tooltip-inner will work.

For more info, check this link -> Tooltip Antd API

like image 43
Luis Paulo Pinto Avatar answered Oct 17 '22 23:10

Luis Paulo Pinto