Martin Schmelzer
Martin Schmelzer

Reputation: 23899

Style material-ui tooltip using @emotion/styled

Is it possible to style material-ui tooltips using the styled function from @emotion/styled?

import { Tooltip } from '@material-ui/core';
import styled from '@emotion/styled';

const MyTooltip = styled(Tooltip)`
    // style the tooltip label
`

I tried using the global Mui classes etc. but did not succeed. I know that an option is to use createMuiTheme and use <ThemeProvider> to apply it, but then the default theme is also applied to the children of the Tooltip component.

Upvotes: 2

Views: 3006

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 81036

The difficulty with styling Tooltip in this manner is that Tooltip doesn't support a className prop (which is what the styled function injects) -- the className prop would simply be forwarded on to the element wrapped by the tooltip.

The solution is to intercept the props passed by styled and leverage the classes prop of Tooltip as shown below:

import React from "react";
import { StylesProvider } from "@material-ui/core/styles";

import Tooltip from "@material-ui/core/Tooltip";
import styled from "@emotion/styled";

const StyledTooltip = styled(({ className, ...other }) => (
  <Tooltip classes={{ tooltip: className }} {...other} />
))`
  font-size: 2em;
  color: blue;
  background-color: yellow;
`;
export default function App() {
  return (
    <StylesProvider injectFirst>
      <StyledTooltip title="Test tooltip">
        <span>Hover over me</span>
      </StyledTooltip>
    </StylesProvider>
  );
}

Edit emotion/styled Tooltip

Related GitHub issue: https://github.com/mui-org/material-ui/issues/11467

Upvotes: 6

Related Questions