Home > Back-end >  In typescript, can I pass JSX.Element as props to styled-components?
In typescript, can I pass JSX.Element as props to styled-components?

Time:03-08

note: Please note that my English is poor.

Here is a component that takes a parent element as props and displays a callout when it is hovered:

const Explanation = styled.span`
  // Detailed implementation is omitted.
  ${(props) => props.parent}:hover & {
    display: inline;
  }
`;

// Examples of Use
<MyButton>Button<Explanation parent={MyButton}>It's MyButton</Explanation></MyButton>

<MyDiv>Div<Explanation parent={MyDiv}>It's MyDiv</Explanation></MyDiv>

When migrating this to typescript, I get a ts(2345) error in the props.parent section.

const Explanation = styled.span<{parent: JSX.Element}>`
  // Detailed implementation is omitted.
  ${(props) => props.parent}:hover & {
    display: inline;
  }
`;

Is it possible to pass JSX.Element as props in typescript?

CodePudding user response:

That's because Parent is not a regular JSX element but StyledComponent so you could declare

import styled, {StyledComponent} from "styled-components";

const Explanation = styled.span<{ parent: StyledComponent<"div", any, {}, never> }>`

to match Parent type, but instead of declaring it explicitly, you can use the type of Parent with typeof.

const Explanation = styled.span<{ parent: typeof Parent }>`

https://codesandbox.io/s/awesome-smoke-ztmcv3?file=/src/App.tsx

  • Related