33

How do I type a dynamic tag in React with TypeScript? Given this code:

interface CompProps {
  tag: string;
}

const MyComponent: React.FunctionComponent<CompProps> = ({
  tag = "div",
  children
}) => {
  const Wrapper = tag;

  return <Wrapper>{children}</Wrapper>;
};

I am getting this error:

Type '{ children: ReactNode; }' has no properties in common with type 'IntrinsicAttributes'. ts(2559)

It seems to me I have to add proper types but I cannot figure out which.

7 Answers 7

43

You can pass in a string as a tag name and use that as you have, but you need to type it properly to get type checking to work. tag should be a key of JSX.IntrinsicElements.

interface CompProps {
  tag: keyof JSX.IntrinsicElements;
}

const MyComponent: React.FunctionComponent<CompProps & React.HTMLAttributes<HTMLOrSVGElement>> = ({
  tag: Wrapper = "div",
  children,
  ...rest
}) => {
  return <Wrapper {...rest}>{children}</Wrapper>;
};

Playground Link

4
  • 1
    keyof JSX.IntrinsicElements only works with html elements. what about custom react components Nov 19, 2020 at 14:10
  • @Pier-Luc Gendreau, could you help please stackoverflow.com/questions/74474194/…
    – Asking
    Nov 17, 2022 at 13:04
  • late comment but for custom react components, maybe we can union their type together and then use the props to detect, or just dynamic import it (if conditionally, use io-ts to check the type could be an option IMO)
    – keikai
    Dec 12, 2022 at 5:54
  • See my answer here to dynamically change the props based on its tag: stackoverflow.com/a/76178335/16649797
    – ccrsxx
    May 5 at 1:55
23

Using A Type definition For All HTML Elements

In order to allow all HTML elements to be used as your tag, you can utilize the keys of the IntrinsicElements interface defined in the JSX namespace. IntrinsicElements appears to contain a mapping of HTML element tags to their respective attributes (includes element-specific attributes). To utilize these keys we can do the following:

interface Props {
  tag?: keyof JSX.IntrinsicElements
}

What if I want to allow React components to be used as the tag?

React defines two interfaces: ComponentClass and FunctionComponent. React also defines a union of these two interfaces that allows you to specify any React component: ComponentType. We can create a union of this and our last definition to allow both components and HTML tags.

import { ComponentType } from 'react';

interface Props {
  tag?: ComponentType | keyof JSX.IntrinsicElements;
}

Well, now I have a tag, what about HTML attributes?

If you want to allow all other HTML attributes to be allowed you can either extend React.HTMLAttributes<Element> to get all of the shared HTML attributes (no element-specific ones) or you can introduce a generic and utilize JSX.IntrinsicElements.

The second option is more complex and comes with a few caveats. You have to use type instead of interface to extend/intersect your Props and the specific attributes defined on a key in JSX.IntrinsicElements. You will also need to use generics on your function so that you can pass them to your Props type which means you can no longer use React.FunctionComponent<Props> since that happens before access to any generics. This means you'll want to add children to your Props definition.

That was a lot of words which I believe are better explained with this example:

// Define our Props type to allow the specifying of a Tag for HTML attributes
// Also define children as React does with React.ReactNode
type Props<Tag extends keyof JSX.IntrinsicElements> = {
  tag?: ComponentType | keyof JSX.IntrinsicElements;
  children?: ReactNode;
} & JSX.IntrinsicElements[Tag];

// Define our generic (Tag) again here and give it our default value
// Don't forget to specify the type Props<Tag> at the end of your function's arguments
// Then we can spread all props to the tag/Wrapper
function MyComponent<Tag extends keyof JSX.IntrinsicElements = 'div'>({ tag: Wrapper = 'div', ...props }: Props<Tag>) {
  return <Wrapper {...props} />;
}

// Example usage, noValidate is typed as
// (JSX attribute) React.FormHTMLAttributes<HTMLFormElement>.noValidate?: boolean | undefined
<MyComponent<'form'> tag="form" noValidate>
  {/* My Form Stuff */}
</MyComponent>;

// You don't need to specify 'div' since it is the default
<MyComponent id="page">
  <p>Just a paragraph inside of a regular div</p>
</MyComponent>;
6
  • 15
    Is it working for others ? I'm getting this TS error when passing the props to Wrapper: Type 'Omit<Props<Tag>, "tag">' is not assignable to type 'IntrinsicAttributes & SVGProps<SVGSymbolElement> & ClassAttributes<HTMLObjectElement>
    – Layvier
    Jul 29, 2021 at 8:22
  • Awesome answer! I thought it wasn't possible to type the props like this. This one achieves a generic way of typing HTMLElements. Good work man!
    – dnarvaez27
    Sep 7, 2021 at 1:54
  • 1
    Why isn't the tag member's type declared as tag?: ComponentType | Tag?
    – pat
    Apr 9, 2022 at 0:01
  • @pat That's a good point. I haven't tested that to see if it works yet but if you have, feel free to submit an edit.
    – Andria
    Apr 17, 2022 at 0:15
  • It would be helpful to add which version of Typescript this works with, because when I paste that into my codebase using v4.8.4 it complains about it.
    – ivarni
    Nov 11, 2022 at 10:22
4

I had a similar problem where I tried to generate a dynamic heading tag based on a passed 'level' prop. It also generated the "Property X does not exist on type IntrinsicAttributes" error.

The code that generated the error was the following;

// Heading.tsx
import React, { FunctionComponent, ReactNode } from 'react';

interface PropsType {
  level: 1 | 2 | 3 | 5 | 6;
  children?: ReactNode;
}

type HeadingTag = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';

const HeadingComponent: FunctionComponent = ({
  level,
  children = null
}: PropsType) => {
  const Tag = `h${level}` as HeadingTag;
  return (
    <Tag>
      {children}
    </Tag>
  );
};

export default HeadingComponent;


// And I used this component all over my codebase like this;
// HomePage.tsx
<Heading level={1}>
  This Is A Title
</Heading>

I solved this by changing:

const HeadingComponent: FunctionComponent = ({
  ... // removed for brevity
}: PropsType) => {
  ... // removed for brevity
};

to:

const HeadingComponent: FunctionComponent<PropsType> = ({
  ... // removed for brevity
}) => { 
  ... // removed for brevity
};
1
  • 1
    Could also do const Tag = `h${level}` as const now and typescript will get the right type. May 20, 2021 at 20:59
3
const YourComponent: React.FC<Props> = ({ tag: Tag = 'button', children, ...props }) => (
  <Tag {...props}>
    {children}
  </Tag>
);
type Props = {
  tag?: keyof JSX.IntrinsicElements;
} & React.HTMLAttributes<HTMLOrSVGElement>;

This works well for me.

1
1

Simple method to use dynamic tag name in React with TypeScript:

export default function Text(props: TextProps) {
  const { text, header } = props;

  let Tag: string;
  if (!header) Tag = "span"; 
  else Tag = `h${header}`;

  const ConstTag = Tag as "span" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6";

  return <ConstTag>{text}</ConstTag>;
}
1

I don't see any answers here that are entirely right. All the answers don't change the props based on the tag used.

Here's the simplified version of the component type that I use at work, it changes the props based on its tag with the default tag included. You also get an error if you put the wrong props to the tag you used, for example trying to put the formAction prop to the div tag.

import type { HTMLAttributes, ComponentPropsWithoutRef } from 'react';

// All valid HTML tags like 'div' | 'form' | 'a' | ...
type ValidTags = keyof JSX.IntrinsicElements;

// Generic type to generate HTML props based on its tag
type CustomTagProps<T extends ValidTags> = {
  tag?: T | ValidTags;
} & (ComponentPropsWithoutRef<T> & HTMLAttributes<HTMLOrSVGElement>);

/**
 * Make the default tag a constant to make it easy to infer both the default
 * generic parameter and the `tag` prop
 */
const DEFAULT_TAG = 'div' as const;

// Use the default `div` tag for both the generic parameter and `tag` prop
export function CustomTag<T extends ValidTags = typeof DEFAULT_TAG>({
  tag = DEFAULT_TAG,
  ...rest
}: CustomTagProps<T>): JSX.Element {
  /**
   * Assign the `tag` prop to a variable `CustomTag` of type ValidTags.
   *
   * The reason for doing this instead of rendering the `<Tag />` right away
   * is that the TypeScript compiler will yell at you with:
   * `Expression produces a union type that is too complex to represent`
   */
  const Tag: ValidTags = tag;

  // Render the custom tag with its props
  return <Tag {...rest}>This is a custom {tag} tag!</Tag>;
}

Let me know if miss anything or if there's an improvement that I can make.

0

2023 Fully supported HTML,React components and SVG

I've Used the answers provided here with a small sprinkle of conditional types in order to enable full support for any type of element including svgs.

A full working example can be found here: https://codesandbox.io/s/condescending-ellis-6ehp44

import React, { FC, ComponentType } from "react";
import { ReactNode, HTMLProps, SVGProps } from "react";
import "./styles.css";

// IntrinsicElements contains a list of all possible native JSX tags
type ValidTags = keyof JSX.IntrinsicElements;
interface DynamicComponentProps<T extends ValidTags> {
  // We will also want to support other react components
  tag?: T | ComponentType;
  children?: ReactNode;
}

// Conditionally use the correct props based on the 'tag' prop
type DyntamicComponentProps<
  T extends ValidTags
> = T extends keyof HTMLElementTagNameMap // Used if the tag is part of HTML
  ? HTMLProps<HTMLElementTagNameMap[T]> // if it's not HTML, let's check if it's an SVG instead
  : T extends keyof SVGElementTagNameMap
  ? SVGProps<SVGElementTagNameMap[T]> // If it's not an SVG, we don't really have any other options
  : {};

const DynamicComponent = <T extends ValidTags>({
  // Casting 'div' into a valid tag name to prevent TS from infering it as a string.
  tag: Tag = "div" as T,
  ...elementProps
}: DynamicComponentProps<T> & DyntamicComponentProps<T>) => {
  return <Tag {...elementProps} />;
};

// Example starts here
const AnotherComponent: FC = () => <div>I'm a React component!@</div>;

export default function App() {
  return (
    <div className="App">
      <DynamicComponent tag="button" type="button">
        Button Content
      </DynamicComponent>
      <DynamicComponent>Is this a real div? or just a fantasy</DynamicComponent>
      <DynamicComponent tag="a" href="http://example.com">
        Some Link
      </DynamicComponent>
      <DynamicComponent tag={AnotherComponent} />
      <DynamicComponent tag="svg">
        <circle
          cx="50"
          cy="50"
          r="40"
          stroke="black"
          stroke-width="3"
          fill="red"
        />
        <text x="0" y="110">
          I'm an SVG!
        </text>
      </DynamicComponent>
    </div>
  );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.