How to create JSX dynamically from Json

About

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:

  • their title
  • their description
  • and their link

Demo

The data

  • The data. A Json array object of articles with a title and a description that you may have fetched from a server.
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 Minimal React Component

A Title component: A minimal function component that returns a minimal jsx

function Title(props) {
  return <h1>{props.title}</h1>;
}

The dynamic Jsx Component

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>
  );
}

Result

A list of page web:





Discover More
React - JSX

JSX is a Javascript HTML Like language that compiles to Javascript React API. The first motivation of JSX is that reading and writing React elements, are easier. It permits to: write JSX elements...



Share this page:
Follow us:
Task Runner