docs icon indicating copy to clipboard operation
docs copied to clipboard

Add: Explain how to render components via variables

Open swift502 opened this issue 1 year ago • 1 comments

I just spent a lot of time trying to figure all this stuff out. Maybe it's worth adding it to the docs?

1. First letter upper case convention

Variable names need to be capitalized correctly. (I understand it's a React/JSX convention) If they're not, component doesn't render. As such, this piece of code just creates a <stored/> element instead of the component stored in the variable.

---
// Store component into a variable
let stored = Component;
---
<!-- Render -->
<stored/>

The "s" in "stored" needs to be upper case. Would it be worth it adding that warning somewhere near the Dynamic HTML section?

2. Storing and rendering

My intuitive understanding of storing a component was this.

---
// Store component into a variable
let Stored = <Component/>;
---
<!-- Render -->
<Stored/>

Of course that doesn't work, because JSX isn't allowed in frontmatter scripts. Instead this is correct.

---
// Store component into a variable
let Stored = Component;
---
<!-- Render -->
<Stored/>

But again, as far as I can tell, the docs have no mention of this.


Would it be worth adding all this info? Maybe provide an expanded example of storing components into variables and rendering them? Let me know what you think. Thanks!

swift502 avatar Aug 12 '22 15:08 swift502

Thanks for the issue! We do document a more basic version of this where HTML tags are set as strings — https://docs.astro.build/en/core-concepts/astro-components/#dynamic-html — but I agree that a brief mention is a good idea!

delucis avatar Aug 15 '22 22:08 delucis

@delucis Yeah I found that basic string tutorial, but still got had to google around and ask on Discord how to pass an imported component to a variable.

The case sensitivity rule is really bad because there's no hint or error to suggest what could be wrong.

swift502 avatar Aug 16 '22 11:08 swift502

Thanks @swift502 for bringing this up!

Do you think this is something that could be combined with the existing example, something of the form:

---
const El = 'div';
let Stored = Component;
---
<El>Hello!</El> <!-- renders as <div>Hello!</div> -->
<Stored /> <!-- renders as a stored component. Note capitalization! -->

Would you like to make a PR with something to this effect? I think it covers all the bases concisely?

sarah11918 avatar Aug 20 '22 16:08 sarah11918

@sarah11918 Sounds good. Will do. 🙂

swift502 avatar Aug 20 '22 16:08 swift502