I need to call this.getFact
from the Animal
component, but using this
raises TypeError: this is undefined
import './App.css';
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
fact: '',
}
}
getFact(endpoint) {
fetch(endpoint)
.then(response => response.json())
.then(data => {
this.setState({
fact: data.text,
});
})
}
Animal(props) {
return (
<div>
<h1>{props.name}</h1>
<button onClick={() => this.getFact(props.endpoint)}>get a {props.name.toLowerCase()} fact</button>
</div>
)
}
render() {
return (
<div className="App">
<div>
<p>{this.state.fact}</p>
</div>
<div className="animals">
<this.Animal name="Dog" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Cat" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Bird" endpoint="https://some-random-api.ml/facts/dog" />
<this.Animal name="Otter" endpoint="https://some-random-api.ml/facts/dog" />
</div>
</div>
);
}
}
export default App;