Home > Blockchain >  TypeScript React: How do I type a component that passes props to an html `img` element?
TypeScript React: How do I type a component that passes props to an html `img` element?

Time:02-10

I have a simple component Bar that passes props to a <img />

function Bar(props: React.HTMLAttributes<HTMLImageElement>) {
  return <img {...props} />;
}

Ideally when I use <Bar /> it should asks me to pass src and alt for the underlying img tag but it is not working that way. Also the autocomplete seems not working.

Live demo: enter image description here

CodePudding user response:

Just press cmd on Mac or ctrl on Windows focusing on the img tag and then click the mouse, you will see IntrinsicElements set.

function Bar(props: React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>) {
  return <img {...props} />
}

CodePudding user response:

Try the below code to define props for your Bar component

function Bar(
props: React.DetailedHTMLProps<
    React.ImgHTMLAttributes<HTMLImageElement>,
    HTMLImageElement
>,) {
return <img {...props} />;
}
  • Related