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.
You can simply pass the dynamic tag name as the first argument to the React. createElement() method (as it accepts a string tag name). For example: const type = (someCondition) ?
You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.
Using TypeScript with Create React AppCreate React App supports TypeScript out of the box. You can also add it to an existing Create React App project, as documented here.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With