I'm making a random quote generator, and, for some reason, I'm not able to pass the information from the API to my state and I can't make the QuoteComponent receive the data as props. Apparently I'm doing everything correctly, but I keep getting 'undefined' when i 'console.log' my state to see if the information is there. here's the code(two simple components, the App and the QuoteComponent):
import React from "react";
import "./styles.css";
import QuoteComponent from "./QuoteComponent";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
qouteData: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch("https://api.quotable.io/quotes")
.then(res => {
return res.json();
})
.then(data => {
this.setState({
quoteData: data
});
});
}
render() {
console.log(this.state.quoteData);
return (
<div className="App">
<QuoteComponent />
</div>
);
}
}
export default App;
QuoteComponent
import React from "react";
import "./styles.css";
function QuoteComponent(props) {
return (
<div className="card">
<div className="container">
<div className="flex">
<div id="quote">
<h2>{props.quote}</h2>
</div>
<div id="quote-a">
<h4>{props.author}</h4>
</div>
<div id="button">
<button onClick={props.handleClick}>New Quote</button>
</div>
</div>
</div>
</div>
);
}
export default QuoteComponent;
You havn't passed props
to the component :
<QuoteComponent />
It should look like this :
<QuoteComponent {...this.state.qouteData} handleClick={your_click_handleer}/>
//OR
<QuoteComponent
quote={this.state.qouteData.quote}
author={this.state.qouteData.author}
handleClick={your_click_handleer}/>
Run the below code snippet, hope that will clear your doubts :
function QuoteComponent(props) {
return (
<div className="card">
<div className="container">
<div className="flex">
<div id="quote">
<h2>{props.content}</h2>
</div>
<div id="quote-a">
<h4>{props.author}</h4>
</div>
<div id="button">
<button onClick={props.handleClick}>Get Random Quote</button>
</div>
</div>
</div>
</div>
);
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
qouteData: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch("https://api.quotable.io/random")
.then(res => {
return res.json();
})
.then(data => {
this.setState({
quoteData: data
});
});
}
render() {
return (
<div className="App">
<QuoteComponent {...this.state.quoteData} handleClick={this.fetchData}/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments