8

I would like to display my json data with reactJs in the table, but I can't.

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },

...

]

The source code in full: http://jsonplaceholder.typicode.com/posts

B--rian
  • 5,578
  • 10
  • 38
  • 89
Mamoudou Ndiaye
  • 137
  • 2
  • 3
  • 13

2 Answers2

14

You can use map to iterate over your JSON data

class App extends React.Component {
  constructor(){
    super() 
      this.state = {
        data: []
      }
    
  }
  componentDidMount() {
    $.ajax({
       url: "http://jsonplaceholder.typicode.com/posts",
       type: "GET",
       dataType: 'json',
       ContentType: 'application/json',
       success: function(data) {
         
         this.setState({data: data});
       }.bind(this),
       error: function(jqXHR) {
         console.log(jqXHR);
       }.bind(this)
    })
  }
  render() {
    
        
    return (
      <table>
      <tbody>{this.state.data.map(function(item, key) {
             
               return (
                  <tr key = {key}>
                      <td>{item.userId}</td>
                      <td>{item.id}</td>
                      <td>{item.title}</td>
                      <td>{item.body}</td>
                  </tr>
                )
             
             })}</tbody>
       </table>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.js"></script>
<div id="app"></div>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • To get JSON data from external link is not a problem. You just need to have and ajax call and then fetch the data, save it in the state and then do the same. What I showed is a demonstration whereby I copied the data in state. – Shubham Khatri Nov 02 '16 at 10:04
  • I tried it , but I have this error: XMLHttpRequest cannot load http://127.0.0.1:8000/assurance/?format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. i fail to access this link – Mamoudou Ndiaye Nov 03 '16 at 11:06
  • Are you trying to load data from this same api that you have posted in question. I think it doesn't support CORS then. Let me check – Shubham Khatri Nov 03 '16 at 11:14
  • thank you, it's work, but I try to replace the link with a local link (127.0.0.1:8080/assurance/?format=json) I have this error: XMLHttpRequest cannot load 127.0.0.1:8000/assurance/?format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. i fail to access this link. – Mamoudou Ndiaye Nov 03 '16 at 15:35
  • It will give your this error because you need to enable CORS in your server. If you are using Node.js server then add `app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });` to your server code. If using another search how to enable CORS and your will get the ans. – Shubham Khatri Nov 03 '16 at 15:43
  • I don't use Node.js, i use django_restframework, so I'll search how to enable CORS . thanks for help – Mamoudou Ndiaye Nov 03 '16 at 16:21
  • I found the solution using the extension chrome "cors extension" – Mamoudou Ndiaye Nov 07 '16 at 13:29
  • Could you please accept this answer now. And cors plugin for chrome will only work in development environment, I think – Shubham Khatri Nov 07 '16 at 15:20
  • It's true, but i use it until i find the solution – Mamoudou Ndiaye Nov 09 '16 at 16:26
8

are you aiming for a component to display data , you can do something like this

<div id="example"></div>

var cols = [
    { key: 'id', label: 'Id' },
    { key: 'userId', label: 'User' },    
    { key: 'title', label: 'Title' },
    { key: 'body', label: 'Body' }
];

var data = [
  {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
];

var Table = React.createClass({

render: function() {
    var headerComponents = this.generateHeaders(),
        rowComponents = this.generateRows();

    return (
        <table>
            <thead> {headerComponents} </thead>
            <tbody> {rowComponents} </tbody>
        </table>
    );
},

generateHeaders: function() {
    var cols = this.props.cols;  // [{key, label}]

    // generate our header (th) cell components
    return cols.map(function(colData) {
        return <th key={colData.key}> {colData.label} </th>;
    });
},

generateRows: function() {
    var cols = this.props.cols,  // [{key, label}]
        data = this.props.data;

    return data.map(function(item) {
        // handle the column data within each row
        var cells = cols.map(function(colData) {

            // colData.key might be "firstName"
            return <td> {item[colData.key]} </td>;
        });
        return <tr key={item.id}> {cells} </tr>;
    });
}
});

React.render(<Table cols={cols} data={data}/>,  document.getElementById('example'));
dicodino
  • 121
  • 4