lukasz-p
lukasz-p

Reputation: 183

Render object in reactjs

I have symfony rest api and I'm writing some frontend for this (1st time using react). So, here is my index.js:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visits: []
        };
    }

    componentDidMount() {
        const url = 'http://localhost/app.php/api/visits?from=2017-05-05&to=2017-05-08';
        axios.get(url)
            .then(response => response.json())
            .then(
                visits => this.setState({visits})
            ).catch(err => err)
    }

    render() {
        return (
            <div>
                <ul>
                    {this.state.visits.map((visit, index) => <li key={index}>{visit}</li>)}
                </ul>
            </div>
        )
    }
}
const app = document.getElementById('app');
ReactDOM.render(<App/>, app);

Response from api looks like:

{
    "2017-05-05":  2,
    "2017-05-06":  8,
    "2017-05-07": 10,
    "2017-05-08":  1,
}

How can i iterate through that and print it to the screen? Now i don't get any errors, just getting response from server but don't have anything on the screen.

Greetings

Upvotes: 1

Views: 5474

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104489

Its not any array, its a object so directly map will not work on that. First we need to use Object.keys() to get all the keys in an array then use map on that.

Like this:

render() {
    let visits = this.state.visits;
    return (
        <div>
            <ul>
                {Object.keys(visits).map((visit, index) => <li key={index}>{visit} : {visits[visit]}</li>)}
            </ul>
        </div>
    )
}

Object.keys: will return an array of all the keys of that object.

Check the working snippet:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visits: []
        };
    }

    componentDidMount() {
        this.setState({
           visits: {
              "2017-05-05":2,
              "2017-05-06":8,
              "2017-05-07":10,
              "2017-05-08":1
            }
        })        
    }

    render() {
      let visits = this.state.visits;
      return (
        <div>
            <ul>
                {Object.keys(visits).map((visit, index) => <li key={index}>{visit} : {visits[visit]}</li>)}
            </ul>
        </div>
    )
  }
}
const app = document.getElementById('app');
ReactDOM.render(<App/>, app);
<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='app'/>

Upvotes: 3

Related Questions