"react js: map over an array of objects to render in jsx" Answer’s

0

Use map to render your data. and store the json as a javascript object in the state itself instead of two seperate arrays.

 <!-- Not present in the tutorial. Just for basic styling. -->
    <link rel="stylesheet" href="css/base.css" />
    <script src="https://npmcdn.com/react@15.3.0/dist/react.js"></script>
    <script src="https://npmcdn.com/react-dom@15.3.0/dist/react-dom.js"></script>
    <script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
    <script src="https://npmcdn.com/jquery@3.1.0/dist/jquery.min.js"></script>
    <script src="https://npmcdn.com/remarkable@1.6.2/dist/remarkable.min.js"></script>
    <div id="content"></div>

    <script type="text/babel">


var UserGist = React.createClass({
  getInitialState: function() {
    return {

     data: [{"id":"103","name":"Atelier graphique"},
  {"id":"112","name":"Signal Gift Stores"},
  {"id":"114","name":"Australian Collectors, Co."},
  {"id":"119","name":"La Rochelle Gifts"},
  {"id":"121","name":"Baane Mini Imports"},
  {"id":"124","name":"Mini Gifts Distributors Ltd."},
  {"id":"125","name":"Havel & Zbyszek Co"},
  {"id":"128","name":"Blauer See Auto, Co."},
  {"id":"129","name":"Mini Wheels Co."},
  {"id":"131","name":"Land of Toys Inc."}]
    };
  },

  componentDidMount: function() 
  {

  },

  componentWillUnmount: function() {
    this.serverRequest.abort();
  },

  render: function() {
            return (
            <div>
        {this.state.data.map(function(item, index){
          return    <li>{item.name} is the company name, {item.id} is the ID</li>

        })}</div>
        );

  }
});


ReactDOM.render(
  <UserGist source="http://localhost/Akshay/REACT/testDataAPI.php?user=2&num=10&format=json" />,
  document.getElementById('content')
); 

    </script>
</html>

JSFIDDLE

For the fiddle example I have deleted your $.get() code in componentDidMount.

P.S. Create the state array data as an array of object as shown in the fiddle example

Wednesday, March 31, 2021
 
edorian
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share