0

I'm very new to react and trying to teach it to myself. Trying to make an API call and loop through the records. I've been successful so far, however, I can't seem to figure out how to create a new line after each element that gets displayed. I'm sure it's something simple that I'm just missing. Can someone advise here?

import React from 'react';

export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            items: [],
            isLoaded: false,
        }
    }

    async componentDidMount() {
        const url = "https://api.randomuser.me/?results=10";
        const response = await fetch(url);
        const data = await response.json();
        this.setState({ person: data, loading: false, len: data.results.length });
    }

    render() {
      let items = [];
      for (let i = 0; i < this.state.len; i++) {
        const item = this.state.person.results[i].name.title;
        items.push(item);
      }
      
      return (
        <div>
          {this.state.loading || !this.state.person ? (
            <div>loading...</div>
          ) : (
            <div>
                {items}
            </div>
          )}
        </div>
      );
    }
  }

1 Answer 1

1

You can use .map() function to loop over the array display it in within the tags.

return (
        <div>
          {this.state.loading || !this.state.person ? (
            <div>loading...</div>
          ) : (
            <div>
                {
                    items.map((item) => (
                        <>
                            <span>{item}</span>
                            <hr />
                        </>
                    )
                }
            </div>
          )}
        </div>
      );
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect just what I needed. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.