#Loading React Components Dynamically

1 messages · Page 1 of 1 (latest)

digital hamlet
#

Any tips on how to load components dynamically? I'm trying to create these aquarium components with jsx props.

Doing this to get it loading on localhost but what changes should I make to get the component available at _astro/component when its deployed?

{fish.map(fishName => {
              const FishComponent = React.lazy(() =>
                import(`./${fishName}.jsx`)
              );
              return <FishComponent key={fishName} />;
            })}
            {decor.map(decorName => {
              console.log(decorName);
              const DecorComponent = React.lazy(() =>
                import(`./${decorName}.jsx`)
              );
              return <DecorComponent key={decorName} />;
            })}
abstract pivot
#

I don't think that's possible. Astro is a server framework that could render React components "on the server" and sending 0 js to the client. Now if you want to do something dynamically on the client side, then you're not on your own, but you don't use Astro, you use the React framework.
here an example, not directly related but maybe can inspire, it's a functional dynamic js loading on the client with an Astro script tag https://github.com/MicroWebStacks/astro-examples#09_dynamic-imports

digital hamlet
tidal lion
#

Hi @digital hamlet I actually needed to do this exact thing in a new project and happy to say I cracked it. Here's how you do it.

You need a file to gather, map, and export your components so something like components.js with something like this:

import { default as Component1 } from './Component1.astro'
import { default as Component2 } from './Component2.astro'
import { default as Component3 } from './Component3.astro'


export const components = {
    Component1: Component1,
    Component2: Component2,
    Component3: Component3,
}

Then, import components from components.js in the file where you want to use these and in that .astro file you can do something like this:

---
import { components } from './components.js'
//..
---

{
    fishNames &&
        fishNames.map((fishName) => {
            const Component = components[fishName]
            if (!Component) return null
            return <Component />
        })
}

With this you can do some really cool things. Let me know if it works but I am using this successfully in a project.

#

(It should work the same way for React components)