This article shows you how to create JSX dynamically from a Json object.
Because jsx is already an expression, you can create JSX from JSX and compose it as you wish.
The below demo will just print a list of article with:
function getJson(){
return [
{
title: "How to create Jsx dynamically",
description: "This article shows you how to create Jsx dynamically from Json.",
url: top.location.href
},
{
title: "foobar",
description: "foobar is a playful allusion to the World War II-era military slang FUBAR (Fucked Up Beyond All Repair).",
url:"https://en.wikipedia.org/wiki/Foobar"
}
];
}
A Title component: A minimal function component that returns a minimal jsx
function Title(props) {
return <h1>{props.title}</h1>;
}
This react function will loop over the data entry and creates the Jsx dynamically.
function App() {
let json = getJson();
/* Creation of the dynamic Jsx */
let jsxDynamic = json.map(
(element, index) => (
<div key={index}>
<Title title={element.title}/>
<p>{element.description} <a href={element.url}>More ...</a></p>
<hr/>
</div>
)
);
return (
<div> {/* Components must return a single root element. This is the why of the ''<div>'' (to contains all the Welcome elements) */}
{jsxDynamic}
</div>
);
}
A list of page web: