Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of dynamic HTML tags #108

Closed
stephenkoo opened this issue Apr 19, 2019 · 3 comments
Closed

Add example of dynamic HTML tags #108

stephenkoo opened this issue Apr 19, 2019 · 3 comments

Comments

@stephenkoo
Copy link
Contributor

stephenkoo commented Apr 19, 2019

Trying to find the "right" @types/react in the advance cheatsheet to use for dynamic HTML tag props. I'm struggling to find the right way of writing this in TS:

import React from "react";

type Props = {
  is?:
    | "h1"
    | "h2"
    | "h3"
    | "h4"
    | "h5"
    | "h6";
  children: React.ReactNode;
};

const Text = ({ is: Element, children }: Props) => (
  <Element>{children}</Element>
);

Text.defaultProps = {
  is: "span"
};

This produces the TS error: JSX element type 'Element' does not have any construct or call signatures

Based on the advanced docs, I've tried writing the is? type as :

  • JSX.InstrinsicElements<"h1"|"h2">
  • React.ReactElement<"h1"|"h2">
  • React.ElementType<"h1"|"h2">

But this isn't working. Any help is much appreciated!

@stephenkoo
Copy link
Contributor Author

I think it has something to do with using union types:
microsoft/TypeScript#28806
microsoft/TypeScript#7294

But I'm not sure how to put it all together.

@eps1lon
Copy link
Member

eps1lon commented Apr 19, 2019

Your is prop is optional. undefined is not a valid element type which is why the type checker rejects this. Mark it as non-nullable in your props and the current typings should be able to pick up that is is optional because of the defaultProps.

@stephenkoo
Copy link
Contributor Author

Ah, is that it? Thanks, @eps1lon!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants