Load Components On Demand in React with 3 Lines of Code

We needed a simple way of saving React components into a database and load them dynamically on our applications

Santi Barbat
1 min readAug 11, 2021

At Comtura we are using React to develop all our applications. At some point this year we realized we needed a simple way of saving components into a database with its properties and load them dynamically on our applications when needed.

Found some good tutorials in the internet but no one really convinced me, they were too long and clanky, so we’ve decided to implement our own solution for React 17 using functional components and the magicReact lazy method.

The Solution

First let’s implement the component two test components that we are going to use that this actually works:

Once we have our test components, let’s implement the logic that would load this components dynamically:

This component will try to load the component specified in the “component” property that needs to be sent to DynamicComponents component when used:

As you can see is as easy as send the component that needs to be loaded and the properties. This is something that you could get from any API and you can store the components that needs to be loaded in a database, with its properties.

Make sure that you have configured the “baseUrl”: “src” in your tsconfig.ts file so that the components can be imported with the absolutes paths.

Thanks for reading and remember to clap if you found this useful.

All the code can be found at https://gist.github.com/sbarbat/

--

--

Santi Barbat

CTO @ Comtura — London, UK — Argentine, tech & BBQ lover 🍖