0% found this document useful (0 votes)
125 views

How To Render A Component Dynamically Based On A JSON Config - Pluralsight

The document discusses how to render a component dynamically in React based on a JSON configuration. It provides a JSON config that specifies the components to render and how they are nested. It also explains how to write a renderer function that uses React.createElement to build and return the component tree based on the JSON input. The complete source code is shown to demonstrate dynamically rendering a card component from Reactstrap using this approach.

Uploaded by

minal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views

How To Render A Component Dynamically Based On A JSON Config - Pluralsight

The document discusses how to render a component dynamically in React based on a JSON configuration. It provides a JSON config that specifies the components to render and how they are nested. It also explains how to write a renderer function that uses React.createElement to build and return the component tree based on the JSON input. The complete source code is shown to demonstrate dynamically rendering a card component from Reactstrap using this approach.

Uploaded by

minal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

Get started Log in

How to Render a
Gaurav Singhal Component
Dynamically Based
on a JSON Config
Gaurav Singhal
Feb 20, 2020 • 11 Min read • 1,136 Views

Feb 20, 2020 • 11 Min read • 1,136 Views

Web Development React

Introduction
Introduction
React makes it super easy to create and
3

Introduction render components dynamically. It


JSON config enables us to build large, fast web apps
Write the Renderer with modern JavaScript. It has scaled
Function
pretty well for the folks at Facebook,
Complete Source
Code Instagram, and many others. One of the
Conclusion coolest features is that you don't have
Top
to use JSX, a template extension to
JavaScript, if you don't want to.

In this guide, instead of using JSX to


How well did this guide solve 2
render theyour
We use cookies to make interactions
with our websites and services easy and
component,
problem? we will use
meaningful. For more information about Disable cookies Accept cookies and close this message
React.createElement() and build the
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 1/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

component based on a JSON config. As


an example for this guide, we'll use the
Reactstrap library and render a card
component.

JSON config
Let's take a look at the JSON config
data and its format.

js
1 const CardConfig = {
2 component: "card",
3 children: [
4 {
5 component: "img",
6 src:
7 "https://images.pexels.com/p
8 },
9 {
10 component: "body",
11 children: [
12 {
13 component: "title",
14 children: "This is a title
15 },
16 {
17 component: "subtitle",
18 children: "This is the sub
19 },
20 {
21 component: "text",
22 children:
23 "Some quick example text
24 },
25 {
26 component: "button",
27 children: "Click Me!"
28 }
29 ] did this guide solve
How well 2
We use cookies to make interactions 30 }
with our websites and services easy and
your problem?
31 ]
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how32 };
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 2/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

This JSON structure corresponds to how


the components are to be nested and
rendered on the page or screen. Notice
that I have added a component key in
the config so that we can map it to the
respective Reactstrap component.
There's also a children key, which
specifies all the child components for
the current component. Its value can be
either a string or an array of
components.

Other than that, we can have additional


keys that we want to pass to the
component as a prop. For example,
here, the src key in the image
component will be given as a prop.

Ideally, the JSON config should be


rendered as shown below.

html
1 <div class="card">
2 <img
3 src="https://images.pexels.com/p
4 class="card-img"
5 />
6 <div class="card-body">
7 <div class="card-title">This is
8 <div class="card-subtitle">This
9 <p class="card-text">
10 Some quick example text to bui
11 the card's content.
12 </p>
13 <button class="btn btn-secondary
14 </div>
15 </div>well did this guide solve
How 2
We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 3/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

Write the Renderer Function


To render the components based on the
component key in the JSON config, we
first need to create an object that maps
the components with the component
key.

js
1 const KeysToComponentMap = {
2 card: Card,
3 img: CardImg,
4 text: CardText,
5 body: CardBody,
6 title: CardTitle,
7 subtitle: CardSubtitle,
8 button: Button
9 };

As you can see, I have mapped the


component key with the corresponding
Reactstrap component.

At the top, we will import all the


required components.

jsx
1 import {
2 Card,
3 CardImg,
4 CardText,
5 CardBody,
6 CardTitle,
7 CardSubtitle,
8 Button
9 } from "reactstrap";

How well did


In the renderer() this guide we
function, solvewill first 2
We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more informationcheck if thecookies
about Disable key exists incookies
Accept the and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 4/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

KeysToComponentMap object.

jsx
1 const renderer = config => {
2 if (typeof KeysToComponentMap[confi
3 // ..
4 }
5 };

Next we will use the


React.createElement() function to
render the component.

React.createElement()

The React.createElement() function


creates and returns a new React
element of the given type.

js
1 React.createElement(
2 type,
3 [props],
4 [...children]
5 );

It takes in three arguments: type ,


props , and children .

The type here is the React component


that we want to render; props is the
data or properties that we want to pass
on to the component, and children is
another component that we want to
pass between the DOM elements.

The JSX we write in React gets


How well did this guide solve 2
We use cookies to make interactions
compiled
with our websites and services easy and
your
to a problem?
React.createElement()
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 5/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

function call with the help of a babel


compiler.

Let's take a look at a simple example.

jsx
1 let WelcomeText = React.createElement
2 "h1",
3 { style: { color: "blue" } },
4 "This is a welcome text"
5 );

The above gets rendered in the DOM as

html
1 <h1 style="color:blue">
2 This is a welcome text
3 </h1>

Now that you understand how


React.createElement() method works,
let's get back to our original quest.

Into the createElement function, we


will pass the component that we want to
render as the first argument, i.e.,
KeysToComponentMap[config.componen
t] . Notice that here to access the
object, we are using the bracket []
notation and not the dot . notation.

jsx
1 function renderer(config) {
2 if (typeof KeysToComponentMap[confi
3 return React.createElement(KeysTo
4 }
5 }
How well did this guide solve 2
We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 6/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

The bracket [] notation allows us to


dynamically access a property using a
variable. Hence, it is easier to get the
component this way, rather than having
a switch case block to determine which
component to render.

If you run the code we have so far, you


will notice that the <Card />
component gets rendered onto the
DOM. That means we are going in the
right direction.

html
1 <div class="card-container">
2 <div class="card"></div>
3 </div>

Now, let's take this further and render


the child components as well.

We need to check if the child


components exist. Then map over each
child component and pass it on to the
renderer() function, making it
recursive.

jsx
1 config.children && config.children.ma

This looks fine. Let's try it out.

jsx
1 function renderer(config) {
2 if (typeof KeysToComponentMap[conf
3 Howreturn
well did this guide solve
React.createElement(
2
We use cookies to make interactions
4
with our websites and services easy and
your problem?
KeysToComponentMap[config.comp
meaningful. For more information about5 Disable cookies
{}, Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here. 6 {
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 7/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

7 config.children && config.ch


8 }
9 );
10 }
11 }

Bummer! If you got the error


config.children.map is not a
function , don't worry; that's because all
children are not the type of an array,
and we have not taken that into
consideration. For instance, the button
component has children of string
type. So let's rewrite our condition.

jsx
1 function renderer(config) {
2 if (typeof KeysToComponentMap[conf
3 return React.createElement(
4 KeysToComponentMap[config.comp
5 {},
6 {
7 config.children &&
8 (typeof config.children ===
9 ? config.children
10 : config.children.map(c =>
11 }
12 );
13 }
14 }

How well did this guide solve 2


We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 8/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

Yay! We got the child components to


render. But wait, we still have an image
component that isn't showing up.

For that, we need to pass the src as a


property in the prop argument.

jsx
1 function renderer(config) {
2 if (typeof KeysToComponentMap[conf
3 return React.createElement(
4 KeysToComponentMap[config.comp
5 {
6 src: config.src
7 },
8 {
9 config.children &&
10 (typeof config.children ===
11 ? config.children
12 : config.children.map(c =>
13 }
14 );
15 }
16 }

How well did this guide solve 2


We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 9/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

There you go. We have successfully


rendered a component dynamically
from a JSON config.

Complete Source Code


In case you get stuck somewhere or
finding it difficult to follow along, this
section has the source code for your
reference.

index.js

jsx
1 import React from "react";
2 import ReactDOM from "react-dom";
3 How well did this guide solve 2
We use cookies to make interactions 4
with our websites and services easy and
your problem?
import App from "./App";
5
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 10/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

6 const rootElement = document.getEleme


7 ReactDOM.render(<App />, rootElement

App.js

jsx
1 import React from "react";
2 import "./styles.css";
3 import RenderCard from "./RenderCard
4 import "bootstrap/dist/css/bootstrap
5
6 const CardConfig = [
7 {
8 component: "card",
9 children: [
10 {
11 component: "img",
12 src:
13 "https://images.pexels.com
14 },
15 {
16 component: "body",
17 children: [
18 {
19 component: "title",
20 children: "This is a tit
21 },
22 {
23 component: "subtitle",
24 children: "This is the s
25 },
26 {
27 component: "text",
28 children:
29 "Some quick example te
30 },
31 {
32 component: "button",
33 children: "Click Me!"
34 }
35 ]
36 }
37 ]
38 }
39 ];How well did this guide solve 2
We use cookies to make interactions 40
with our websites and services easy and
your problem?
41 export default function App() {
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how42 return (
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 11/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

43 <div className="App">
44 <div className="card-container
45 {CardConfig.map(config => Re
46 </div>
47 </div>
48 );
49 }

RenderCard.js

jsx
1 import React from "react";
2 import {
3 Card,
4 CardImg,
5 CardText,
6 CardBody,
7 CardTitle,
8 CardSubtitle,
9 Button
10 } from "reactstrap";
11
12 const KeysToComponentMap = {
13 card: Card,
14 img: CardImg,
15 text: CardText,
16 body: CardBody,
17 title: CardTitle,
18 subtitle: CardSubtitle,
19 button: Button
20 };
21
22 function renderer(config) {
23 if (typeof KeysToComponentMap[conf
24 return React.createElement(
25 KeysToComponentMap[config.comp
26 {
27 src: config.src
28 },
29 config.children &&
30 (typeof config.children ===
31 ? config.children
32 : config.children.map(c =>
33 );
34 }
How well did this guide solve 2
We use cookies to make interactions 35 }
with our websites and services easy and
your problem?
36
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how37 export default renderer;
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 12/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

Conclusion
Creating and rendering components
dynamically can be very helpful when
the JSON config data is stored in a
database and retrieved by the app
during runtime. The downside to this
approach is that the client or the
browser must know which components
are going to be used so that it can map
with the React elements. Any change in
the JSON schema will break the
renderer() function.

Nevertheless, this approach is widely


used in popular CMS platforms like
WordPress, and I'm pretty sure if you
write it wisely, you can use it in your
applications. That's it from this guide. I
hope you learned something new today.
Until next time, happy coding.

LEARN MORE
How well did this guide solve 2
We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 13/14
02/05/2020 How to Render a Component Dynamically Based on a JSON Config | Pluralsight

SOLUTIONS

Pluralsight Skills (/product/skills)

Pluralsight Flow (/product/flow)

Gift of Pluralsight (/gift-of-pluralsight)

View Pricing (/pricing)

Contact
WeSales (/product/contact-sales)
use cookies to make interactions with our websites and services easy and meaningful. For more
information about the cookies we use or to find out how you can disable cookies, click here (/privacy).

ACCEPT COOKIES AND CLOSE THIS


MESSAGE

PLATFORM Disable cookies

How well did this guide solve 2


We use cookies to make interactions
with our websites and services easy and
your problem?
meaningful. For more information about Disable cookies Accept cookies and close this message
the cookies we use or to find out how
you can disable cookies, click here.
https://www.pluralsight.com/guides/how-to-render-a-component-dynamically-based-on-a-json-config 14/14

You might also like