I’ve recently been working with headless CMSs for clients and noticed a common request: more flexibility when creating a page. The problem? How to achieve the desired outcome while architecting a scalable and maintainable solution for engineers. This pattern eliminates the need for conditional statements when rendering top-level page components. It's especially useful with headless CMSs where content authors need flexibility in arranging components on a page.
When components need to be placed dynamically based on their order in the data, we need to conditionally render each component type and assign the appropriate rendering component.
While there are several approaches to this, developers commonly fill their components with multiple conditional statements to render the correct one. (See screenshot)
While this approach technically works, imagine the complexity with dozens of top-level components—the file would become difficult to debug and risky to modify without introducing regressions.
Let's improve this approach by cleaning up the code structure. Instead of consolidating all rendering logic in one file, we'll separate it so each file handles a single responsibility.
We'll create a mapping object to organize our components.
Start by declaring your component mapping. The key represents the identifier from your CMS or data source, and the value specifies which component to render.
With our map in place, we can now retrieve the correct component directly from the object. If no matching component exists, we return null to prevent rendering.
This approach offers a more scalable solution to the problem. Rather than keeping all logic in a single file, you maintain an object that maps component names to their corresponding UI components.
With this approach, components will display in the correct order based on your data source, without requiring developers to modify any markup or component structure.