Reputation: 161
I am getting an error that I am not able to figure, its about a function that takes an array and returns a random value from it. I used the same function last time and there was no such error
helpers.js
function choice(arr) {
let randomIndex = Math.floor(Math.random() * 3);
return arr[randomIndex];
}
export { choice };
box.js
import React, { Component } from 'react';
import {choice} from './helpers';
import './Box.css'
class Box extends Component {
static defaultProps = {
allColors: ["purple", "magenta", "violet", "pink"]
};
constructor(props){
super(props);
this.state = {color: choice(this.props.allcolors)};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
}
render(){
return(
<div className="Box" style={{backgroundColor: this.state.color}
} onClick={this.handleClick}>
</div>
);
}
}
export default Box;
Upvotes: 1
Views: 110
Reputation: 1047
There are two mistakes in your code:
this.props.allcolors
is undefined
, because you have set the prop allColors
with uppercase "C"choice
, won't give you your desired result. It now only works correctly for arrays of length 3. To fix this, you could change 3
into arr.length
like so:function choice(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
return arr[randomIndex];
}
Upvotes: 6