Passing Astro components to React components
In an Astro site page I wanted to add some bit of interactivity, and chose React.
I created the component, and inside it I had a pro
state variable that was true
or false
and showed different things based on this state:
import { useState } from 'react'
export default function TabBar() {
const [pro, setPro] = useState(false)
return (
<div>
{pro ? <p>pro</p> : <p>free</p>}
</div>
)
}
and I used it like this:
<TabBar client:load />
(client:load
otherwise itโs server-rendered at build time and not interactive).
So far so good.
But I wanted to pass multiple Astro components to this, so hereโs what I did:
<TabBar client:load>
<div slot='free'>
<Free />
</div>
<div class='pt-2 mb-20' slot='pro'>PRO</div>
</TabBar>
Inside the React component, those slots are available through {props.pro}
and {props.free}
.
import { useState } from 'react'
export default function TabBar(props) {
const [pro, setPro] = useState(false)
return (
<div>
{pro ? props.pro : props.free}
</div>
)
}
โ Download my free JavaScript Handbook!
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X