Hi there,
I completed project 1 of the Front End library using React only, and I wanted to get some feedback on the use of React, mainly the logic of it, and if components are created correctly.
Here is the code:
import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";
const api_link = 'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json'
class Quote extends React.Component{
constructor(props){
super(props);
this.state = {
msg: [],
randomIndex: Math.floor(Math.random()),
quote: '',
author: ''
};
this.changeQuote = this.changeQuote.bind(this);
}
changeQuote(){
this.setState({
randomIndex: Math.floor(Math.random()*this.state.msg.length),
quote: this.state.msg[this.state.randomIndex]['quote'],
author: this.state.msg[this.state.randomIndex]['author']
})
}
componentDidMount() {
//document.body.style.backgroundColor = "red"
fetch(api_link, {
headers : {
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(data => this.setState(
{randomIndex: Math.floor(Math.random() * data.quotes.length),
msg:(data.quotes),
quote: data.quotes[this.state.randomIndex]['quote'],
author: data.quotes[this.state.randomIndex]['author']
},))
}
render() {
var twitterUrl = "https://twitter.com/intent/tweet?hashtags=quotes&text=" + encodeURIComponent('"' + this.state.quote + '" -' + this.state.author)
return(
<div id="wrapper">
<div id="quote-box">
<h3 id="text">{this.state.quote}</h3>
<p id="author">- {this.state.author}</p>
<button id="new-quote" onClick = {this.changeQuote}>Change Quote</button>
<a id="tweet-quote" href={twitterUrl}>Tweet</a>
</div>
</div>
)}
}
ReactDOM.render(<Quote/>, document.getElementById('root'));
Thanks