Home > Mobile >  Calling a function from Render - React
Calling a function from Render - React

Time:03-18

I'm trying to call a function called makeMap in render function. Everything is being printed out to the console, however, it doesn't update the HTML. Would love to know what I'm doing wrong and what's the right way to do that. :)

import React from "react";
import axios from "axios";

export default class CountryList extends React.Component {
    state = {
        countries: []
    }

    componentDidMount() {
        axios.get(`https://restcountries.com/v2/all?fields=name,region,area`)
        .then(res => {
            const countries = res.data;
            this.setState({ countries });
        })
    }

    makeMap() {
        this.state.countries.map(country => {
                console.log("aaaaaaaaa");
                return (<li key={country.name}>{country.name}</li>)
        })
    }

    render() {
        return(
            <div>
                {this.makeMap()}
            </div>
        )
    }
}

CodePudding user response:

You may change the makeMap() function as below:

makeMap() {
    return this.state.countries.map(country =>                 
      (<li key={country.name}>{country.name}</li>)
    )
}
  • Related