#TS error on dynamic component

3 messages · Page 1 of 1 (latest)

raw viper
#

This code is causing A TS error, but Astro renders the component correctly. The error is "Component 'Element' is not a valid component."
What's wrong with it?

import type { HTMLAttributes } from "astro/types";
interface Props extends HTMLAttributes<"a">{
Element: String;
classList: String;
}
const { classList, ...attrs } = Astro.props;

let { Element } = Astro.props;
console.log("Element:", Element)
console.log("attrs:", attrs)
if (!Element) Element = attrs?.href ? "a" : "button";

<Element class:list={["button", classList]} {...attrs}>
<span class="label">
<slot />
</span>
</Element>

fallow yarrowBOT
#

Hi @raw viper. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The error you're encountering is likely due to the way Astro handles dynamic tags. According to the Astro documentation (https://docs.astro.build/en/basics/astro-syntax/#dynamic-tags), there are a few important things to note when using dynamic tags:

  • Variable names must be capitalized. For example, use Element, not element. Otherwise, Astro will try to render your variable name as a literal HTML tag.
  • Hydration directives are not supported. When using client:* hydration directives, Astro needs to know which components to bundle for production, and the dynamic tag pattern prevents this from working.
  • The define:vars directive (https://docs.astro.build/en/reference/directives-reference/#definevars) is not supported.

In your case, it seems like you're correctly capitalizing the Element variable. However, the TypeScript error might be due to the fact that Element is initially defined as a String in your Props interface, but later used as a component. TypeScript might be expecting Element to be a valid component type, not a string.

One possible solution could be to define Element as a component type in your Props interface, if possible. However, this might not be feasible if Element can be either a string or a component.

If you're still encountering issues, it might be helpful to create a GitHub issue to alert the Astro team of the problem, as suggested in the Astro documentation (https://docs.astro.build/en/reference/error-reference/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: