How to map JSON data in react js?

Viewed 10245

I want to map JSON data in key-value manner. I tried it doing on stackblitz but it is showing error.

THE CODE I WROTE:

import React from "react";
import ReactDOM from "react-dom";

const sampleJSON = {
  name: "Pluralsight",
  number: 1,
  address: "India",
  website: "https://www.pluralsight.com/"
};

function App() {
  return (
    <div>
      {Object.keys(sampleJSON).map((key, i) => (
        <p key={i}>
          <span>Key Name: {key}</span>
          <span>Value: {sampleJSON[key]}</span>
        </p>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("app"));

THE ERROR I AM GETTING IS:

Error in /turbo_modules/react-dom@17.0.0/cjs/react-dom.development.js (26083:13) Target container is not a DOM element.

https://stackblitz.com/edit/react-lyrp91

3 Answers

You must export default react components. I got it working in a sandbox (link), by changing this line

ReactDOM.render(<App />, document.getElementById("app"));

to this

export default App;

You need to export your app component instead of rendering it to the element id app. The problem is it tries to find element id app, but it can't find in the DOM. However index.js do the same thing, so you don't have to do the ReactDOM.render thing.

ReactDOM.render(<App />, document.getElementById("root")); // you will find this line in index.js, you don't need to do this in app.js

Stackblitz Link

import React from "react";

const sampleJSON = {
  name: "Pluralsight",
  number: 1,
  address: "India",
  website: "https://www.pluralsight.com/"
};

export default function App() {
  return (
    <div>
      {Object.keys(sampleJSON).map((key, i) => (
        <p key={i}>
          <span>Key Name: {key}</span>
          <span>Value: {sampleJSON[key]}</span>
        </p>
      ))}
    </div>
  );
}

You have set state and then in render function add "map" and return html.

  render()
  {
   
    return(
     <div className='training'>
          <div className='items'>
            {
              this.state.training.map( (row,index)=>{
                 return(
                    <h1>{index}</h1>    
                 )                 
              }) 
            }             
          </div>
     </div>
    )
  }
}
Related