ngahu daniel
ngahu daniel

Reputation: 69

Accessing json file in react js

This is my code:

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          name: 'Jal Irani',
          imgURL: './man.jpg',
          hobbyList: ['Front-end Web Development', 'Back-end Web Development', 'Eating Free Food'],
        },
      ],
    };
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Profiler</h1>
        </header>
        <p className="App-intro">//access the json data here</p>
      </div>
    );
  }
}

I want to access the json element in

<p className="App-intro">//access the json data here. 

I have tried to use react map function without success.

Is there any help. AM new in react js.

Upvotes: 1

Views: 899

Answers (3)

Naor Tedgi
Naor Tedgi

Reputation: 5717

import React from "react";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          name: "Jal Irani",
          imgURL: "./man.jpg",
          hobbyList: [
            "Front-end Web Development",
            "Back-end Web Development",
            "Eating Free Food"
          ]
        }
      ]
    };
  }

  render() {
    const { name, imgURL, hobbyList } = this.state.data[0];
    console.log(name);
    console.log(imgURL);
    console.log(hobbyList);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Profiler</h1>
        </header>
        <p className="App-intro" />
      </div>
    );
  }
}

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11270

You can render the data like this:

<p className="App-intro">
  <span>{this.state.data[0].name}</span>
  {this.state.data[0].hobbyList.map(e => <span key={e}>{e}</span>)}
</p>

Upvotes: 1

Artem Mirchenko
Artem Mirchenko

Reputation: 2170

Did you tried to map over your state data object?

render() {
 return (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h1 className="App-title">Welcome to Profiler</h1>
    </header>

 {this.state.data.map((dataItem, i) => 
    <div key={i}>
      <span>{dataItem.name}</span>
      <img src={dataItem.imgURL}/>
      <ul>
        {dataItem.hobbyList.map((item, i) => <li key={i}>{item}</li>)}
      </ul>
    </div>
  )}
  </div>
);
}

Upvotes: 1

Related Questions