Hi Everyone!
I’m starting with the Frontend Projects and the first one is the random quote machine.
I managed to get a new random quote and background color when I click the button, but sometimes I get a strange message saying this:
TypeError: quoteArr[numRan] is undefined
getRan
C:/Users/ezzep/Documents/React/Demo/myapp/src/components/App.js:73
70 | document.body.style.background = colorArr[ranCol];
71 |
72 | this.setState({
> 73 | quote: quoteArr[numRan].quote,
^ 74 | name: quoteArr[numRan].name,
75 | color: colorArr[ranCol]
76 | })
this is inside my getRan method which is called when I click the “new quote” button.
getRan calls a function getRandom() and saves the number in numRan which is then used to access a random element from the quotes Array
quoteArr[numRan] like that.
the problem is that this button works most of the time. After a few tries, that error appears.
Any suggestions?
full code for App.js here:
const colorArr = [
"rgba(165, 139, 124, 1)",
"rgba(199, 102, 4, 1)",
"rgba(255, 255, 255, 1)",
"rgba(255, 241, 137, 1)",
"rgba(183, 183, 183, 1)",
"rgba(154, 206, 201, 1)",
"rgba(237, 106, 90, 1)",
"rgba(244, 241, 187, 1)",
"rgba(230, 235, 224, 1)",
"rgba(54, 201, 198, 1)",
"rgba(154, 206, 201, 1)",
"rgba(187, 190, 100, 1)",
"rgba(142, 85, 114, 1)",
"rgba(242, 247, 242, 1)",
"rgba(68, 56, 80, 1)"
];
const quoteArr = [
{
quote: "una frase",
name: "John"
},
{
quote: "dos frase",
name: "Carl"
},
{
quote: "tres frase",
name: "Dan"
}
];
const numRan = getRandom();
const ranCol = getColor();
document.body.style.background = ranCol;
function getRandom(){
return Math.round(Math.random()*quoteArr.length)
}
function getColor(){
return Math.round(Math.random()*colorArr.length)
}
class App extends React.Component {
constructor(){
super();
this.state = {
quote: quoteArr[numRan].quote,
name: quoteArr[numRan].name,
color: colorArr[ranCol]
}
this.getRan = this.getRan.bind(this);
}
getRan(){
const numRan = getRandom();
const ranCol = getColor();
document.body.style.background = colorArr[ranCol];
this.setState({
quote: quoteArr[numRan].quote,
name: quoteArr[numRan].name,
color: colorArr[ranCol]
})
}
render(){
return (
<div style={{color:ranCol}} id="quote-box">
<div>
<Frase quote={this.state.quote} name={this.state.name} />
</div>
<button onClick={this.getRan} style={{background:this.state.color,color:"white"}}>Generar</button>
</div>
)
}
}