A
A
Anton2016-12-01 08:50:23
JavaScript
Anton, 2016-12-01 08:50:23

How to get json from outside in reactjs?

Good morning everyone!
Tell me how to get json (for example, jsonplaceholder.typicode.com/comments from here)
and display it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Michael, 2016-12-01
@Ooos

Could be something like this

getInitialState: function() {
  return {
    data: []
  }
},
componentWillMount: function() {
  fetch('http://jsonplaceholder.typicode.com/comments')
    .then((res) => {
      res.json().then((data) => {
        this.setState({
          data: data
        })
      })
    })
    .catch((err) => {
      console.log(err)
    })
}

I
iBird Rose, 2016-12-01
@iiiBird

I don’t know how to react, but for Angular 2 - like this: plnkr.co/edit/oz71BFDAeeTwjwW5zqEY?p=preview
ps well, you never know) you might change your mind)

A
Anton, 2016-12-09
@Ooos

Implemented as follows
I throw off the finished solution:

import React from 'react';
import $ from 'jquery';

class App extends React.Component {
   render() {
      return (
         <div>
            <Header/>
            <Content/>
         </div>
      );
   }
}

class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>Title</h1>
         </div>
      );
   }
}

class Content extends React.Component {
    constructor() {
        super()
        this.state = {
            data: []
        }
    }
    componentDidMount() {
        $.ajax({
            url: "http://jsonplaceholder.typicode.com/users",
            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.name}</td>
                        <td>{item.email}</td>
                    </tr>
                )
            })}</tbody>
            </table>
        )
    }
}


export default App;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question