Yanshof
Yanshof

Reputation: 9926

Cant see img on my react - ( code )

I add jquery into my index.html But i don't know why i can't see the avatar_url and the name of the incoming date

I check - the date is valid ( remove the login name here )

How to see the image and the name ? what i did wrong ?

var Card = React.createClass({

  getInitialState: function(){
    return {};
  },

  componentDidMount: function(){

    // we need to define the callback info as component => to get the prop/state
    var component = this;

    // get data ( name ) from AJEX info => the return object is the arg 'data' 
    $.get("https://api.github.com/users/" + this.props.login, function(data){

      component.setState(data);    // set component as component of the callback data => in h3 we can get the data to show on ui 


    });
  },

  render: function(){
    return (
      <div>
        <img src={this.state.avatar_url} width="80"/>
        <h3>{this.state.name}</h3>
        <hr/>
      </div>
    );
  }
});




var Main = React.createClass({
  render: function(){
    return (
      <div>
        <Card login="myLogInName" />
      </div>
    )
  }
});

React.render(<Main />, document.getElementById("root"));

Upvotes: 0

Views: 67

Answers (2)

MEnf
MEnf

Reputation: 1522

Creating components using React.createClass was deprecated after the v.16 update for Reactjs. In order to create a react component in this way, you need to include the create-react-class package at the top of your file using var createReactClass = require('create-react-class');

Upvotes: 1

Brett DeWoody
Brett DeWoody

Reputation: 62881

It looks like the name property is null in the response. As an alternative I've used the login property since it as a value.

I've also updated the code to use ES6 syntax, one advantage of which is arrow functions to auto-bind this.

class Card extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      avatar_url: null,
      login: null
    };
  }

  componentDidMount = () => {
    // get data ( name ) from AJAX info => the return object is the arg 'data' 
    $.get("https://api.github.com/users/" + this.props.login, data => {
      this.setState(data);
    });
  }

  render(){
    return (
      <div>
        <img src={this.state.avatar_url} width="80"/>
        <h3>{this.state.login}</h3>
        <hr/>
      </div>
    );
  }
};


class Main extends React.Component {
  render(){
    return (
      <div>
        <Card login="myLogInName" />
      </div>
    )
  }
};

ReactDOM.render(<Main />, document.getElementById("root"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Upvotes: 2

Related Questions