5

I'm new to react. I dont know how to import json data in one of my component.

This is my json data:

[
    {
        "id": 1,
        "firstname": "abc",
        "lastname": "xyz",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
    },
    {
        "id": 2,
        "firstname": "def",
        "lastname": "uvz",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
    }
]

Here is list Component :

<Container>
  <Grid>
    <Grid.Row>
      <Grid.Column>
        <Header>List</Header>
        <List>
          <List.Item block>
            <List.Content>FirstName and Last Name</List.Content>
            <List.Content>Phone</List.Content>
          </List.Item>
        </List>
      </Grid.Column>
    </Grid.Row>
  </Grid>
</Container>

Can anyone help me in displaying the list? Thanks in advance

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Sanjana
  • 286
  • 2
  • 7
  • 20

4 Answers4

7

You can import contacts from your data.json, and use the map() to iterate and display contacts.

import React, { Component } from "react";
import { Container, Grid, Header, List } from "semantic-ui-react";
import contacts from './data.json';

class App extends Component {

  render() {
    return (
      <Container>
        <Grid>
          <Grid.Row>
            <Grid.Column>
              <Header>List</Header>
              <List>
                {contacts.map(el => {
                  return (
                    <List.Item  key={el.id}>
                      <List.Content>
                        {el.firstname} {el.lastname}
                      </List.Content>
                      <List.Content>{el.phone}</List.Content>
                    </List.Item>
                  );
                })}
              </List>
            </Grid.Column>
          </Grid.Row>
        </Grid>
      </Container>
    );
  }
}

export default App;

Playground:

https://codesandbox.io/s/so-semantic-ui-jfobr

But I think using Table component from semantic-ui-react would be a better for this.

import React, { Component } from "react";
import {  Table } from "semantic-ui-react";
import contacts from './data.json';

class App extends Component {

  render() {
    return (
      <Table singleLine>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell>Id</Table.HeaderCell>
            <Table.HeaderCell>Fullname</Table.HeaderCell>
            <Table.HeaderCell>Phone</Table.HeaderCell>
            <Table.HeaderCell>Email</Table.HeaderCell>
          </Table.Row>
        </Table.Header>

        <Table.Body>
          {contacts.map(el => {
            return (
              <Table.Row key={el.id}>
                <Table.Cell>{el.id}</Table.Cell>
                <Table.Cell>
                  {el.firstname} {el.lastname}
                </Table.Cell>
                <Table.Cell>{el.phone}</Table.Cell>
                <Table.Cell>{el.email}</Table.Cell>
              </Table.Row>
            );
          })}
        </Table.Body>
      </Table>
    );
  }
}

export default App;

Playground for Table version:

https://codesandbox.io/s/so-semantic-ui-28rq9

Docs:

https://reactjs.org/docs/lists-and-keys.html

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
  • Is it possible to create search for the list? – Sanjana Nov 15 '19 at 17:27
  • @Sanjana if you mean in table, semantic-ui-react's Table component does not built-in search functionality. Of course it can be manually done, but some other UI frameworks have this built-in functionality like antd react. https://ant.design/components/table/#components-table-demo-head – SuleymanSah Nov 15 '19 at 17:31
  • @Sanjanaf or manual search, I found a sample here: https://codepen.io/Natarajah/pen/mAGQpw – SuleymanSah Nov 15 '19 at 17:36
  • Just search in google, for "react search in list", you will see lots of tutorials. – SuleymanSah Nov 15 '19 at 17:39
  • thank you so much for helping me. Could you please help me how to execute successfully when fetching through the api link without any error – Sanjana Nov 26 '19 at 13:39
  • @Sanjana you had better to ask a new question about that. I will try to help in that question. – SuleymanSah Nov 26 '19 at 13:47
  • sorry, I'll ask in another question – Sanjana Nov 26 '19 at 13:55
  • what if we want to add search, sort and filter to this list? how do we do that? – uberrebu Aug 08 '21 at 03:02
1

If you want to import that data to your component from another file you can basically export the object where the data exists.

data.js

export default [
    {
        "id": 1,
        "firstName": "abc",
        "lastName": "xyz",
    },

    {
        "id": 2,
        "firstName": "def",
        "lastName": "uvz",
    }
]

In your react component you can then import your json data by doing

import data from './data.js'

You will need to iterate over your json data to pass necessary information to your component

{data.map(person => {
   return (
    <List.Item block key={person.id}>
       <List.Content>
         {person.firstName} and {person.lastName} 
       </List.Content>
     <List.Content>{person.phone}</List.Content>
    </List.Item>
   )
})}

Heads up! List elements need a key property as well otherwise react wil throw an error

This will create a List.Item component for each data entry you have regarding the people and then by accessing the firstName, lastName, phoneon person object you will be able to pass that data to your component.

Example

https://codesandbox.io/s/angry-chebyshev-djxq0?fontsize=14

Ozan
  • 1,623
  • 3
  • 13
  • 25
0

There are several ways to import JSON data within a React component:

  1. Use ES6 imports and exports
  2. Add the JSON data in a file within your public folder, assuming you initialized your project with Create React App, then fetch said data within your componentDidMount() method, and lastly add the fetched data to your component's state.
  3. If the data is static, you could just add it to your component's state when you initialize your component.

Implementation 1:

Add your JSON data in file, for example People.js:

const peopleData = [
    {
        "id": 1,
        "firstname": "abc",
        "lastname": "xyz",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
    },

    {
        "id": 2,
        "firstname": "def",
        "lastname": "uvz",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
    }
];

export default peopleData;

Then within your component, import it like so:

// myPeopleData will contain your json data
import myPeopleData  from '<Relative_Path>/People.js';

For more information about ES6 imports and exports check out this great cheatsheet.

Implementation 2:

  1. Add a file within your public directory containing your JSON data, lets assume it's called people.json
  2. Within your component, add in the componentDidMount() lifecycle method then fetch your data.
  3. Add your fetched data to your component's state.

Your component might look something along the lines of:

import React, { Component } from "react";
import { Container, Grid, Header, List } from "semantic-ui-react";

class MyComponent extends Component {
  state = {
    peopleData: []
  };

  componentDidMount() {
      fetch('./people.json')
        .then(response => response.json())
        .then(data => this.setState({ peopleData: data }));
  }

  render() {
    ...
  }
}

export default MyComponent;

Lastly, Implementation 3:

Within your component just add your data as part of it's default state:

import React, { Component } from "react";
import { Container, Grid, Header, List } from "semantic-ui-react";

class MyComponent extends Component {
  state = {
    peopleData: [
      {
        "id": 1,
        "firstname": "abc",
        "lastname": "xyz",
        "phone": "+91 789654123",
        "email": "abcyz@gmail.com"
      },
      {
        "id": 2,
        "firstname": "def",
        "lastname": "uvz",
        "phone": "+91 123456987",
        "email": "defvu@gmail.com"
      }
    ]
  };

  render() {
    ...
  }
}

export default MyComponent;

Regardless of the approach you take to import your JSON data, you will need to map through your resulting array within your render() method. For more information about Array.protoype.map() method check out MDN's documentation as well as React's Documentation for mapping through lists and rendering list items. Both of which are fantastic resources.

Hopefully that helps!

Nathan
  • 7,853
  • 4
  • 27
  • 50
  • Thank you so much. This works!.. Thank you for explaining briefly with example and documentation :) – Sanjana Nov 15 '19 at 16:38
  • Thanks everyone for helping me in knowing more about reactjs and how to implement json data into the component and how to retrieve the data into the component, I learnt alot. Thank you so much for assisting me :) – Sanjana Nov 15 '19 at 16:53
0

constructor(props) {
super(props);
this.state = {
  loadedList: [],
  lists: [],
};
  }

componentDidMount() {
  
  // after 3001/ write your .json file directory
  
  axios.get('http://localhost:3001/../static/data/terrifdata.json')
      .then(response => {
       this.setState({
         lists: response.data,
         loadedList: response.data,
         isLoading: false
        })
    })
 }

<div>
{loadedList.map((postDetail, index) => {
                    return (
                  <h5>
                     {postDetail.name}
                  </h5>
                  )}
               }
</div>
Khadim H.
  • 549
  • 5
  • 8