I am trying to build a COVID-19 tracker app using react and materialize CSS framework. I am trying to get some data using an external API and put them into a drop-down menu. I can console.log the results, it is fine. But when I try to put that data into a drop-down menu, that drop-down menu isn't responding. When I tried with hardcoded values it is working fine.
This is my App.js. I don't have any components except App.js
import React, { Component } from "react";
import "./App.css";
import "materialize-css/dist/css/materialize.min.css";
import M from "materialize-css";
class App extends Component {
constructor() {
super();
this.state = { countries: [] };
}
async componentDidMount() {
document.addEventListener("DOMContentLoaded", function () {
const elems = document.querySelectorAll("select");
M.FormSelect.init(elems, {});
});
const call = await fetch('https://disease.sh/v3/covid-19/countries');
const result = await call.json();
const countries = result.map( (country) => (
{
name: country.country,
value: country.countryInfo.iso2
}
));
this.setState({countries:countries});
};
render = () => {
return (
<div className="App">
<h3>COVID-19 TRACKER</h3>
<div className="input-field col s12">
<select>
{this.state.countries.map( (country) => {
return <option value={country.name}>{country.name}</option>
})}
</select>
</div>
</div>
);
};
}
export default App;
document.addEventListener("DOMContentLoaded")
should be placed outside your componentDidMount
override as it is a global event.
Don't use vanilla DOM selection and manipulation like document.querySelectorAll()
if you want to use React at all, React keeps its own DOM tree and updates it based on state changes. Instead, rely on render()
re-executing every time the state is changed, so what you want to do is to change the state.
Every time you use map
to generate lists of items, provide unique keys
to uniquely identify the items in the React tree. Your data source doesn't provide ISO codes for all elements so it's not a reliable item key. I have used here the index (i.e. counter) from the map
function but ideally you should aggregate a reliable unique identifier from the data itself.
Here's a working code: