1

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

2
  • Did you tried to call your function in componentDidMount? Commented Dec 14, 2019 at 17:04
  • No, I am a beginner and dont know much about lifecycle methods. I was just following a tutorial and double checked the code many times, yet in tutorial it works but not in mine Commented Dec 14, 2019 at 17:06

1 Answer 1

6

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

That happens from time to time... you're welcome! You could mark this answer as accepted if you like :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.