Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing a dynamic tag in React with TypeScript?

Tags:

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.

like image 634
Lukas Avatar asked May 03 '19 12:05

Lukas


People also ask

How do I add a dynamic tag in React?

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) ?

How do you pass a tag as a prop in React?

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.

Can we write TypeScript in React?

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.


1 Answers

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

like image 127
Titian Cernicova-Dragomir Avatar answered Sep 19 '22 14:09

Titian Cernicova-Dragomir