Vaibhaw kr
Vaibhaw kr

Reputation: 161

React js error in a simple function that takes an array and returns a random value

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;

here is the error enter image description here

Upvotes: 1

Views: 110

Answers (1)

Wouter Raateland
Wouter Raateland

Reputation: 1047

There are two mistakes in your code:

  1. this.props.allcolors is undefined, because you have set the prop allColors with uppercase "C"
  2. This might not be a problem in your specific scenario, but in general, the function 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

Related Questions