0

I have a file let's say Colors.js which contains some hex values as follows:

module.exports = {

  red50:    '#ffebee',
  red100:   '#ffcdd2',
  red200:   '#ef9a9a',
  red300:   '#e57373',
  red400:   '#ef5350',
  red500:   '#f44336',
  red600:   '#e53935',
  red700:   '#d32f2f',
  red800:   '#c62828',
  red900:   '#b71c1c'

};

What I'm trying in another file is is to randomly take the above-defined objects and assign them as inline-css backgroundColor after importing Colors.js file

So eventually instead of defining one of them manually as follows:

import Colors from "../Colors";
module.exports = function() {
    return {
        someStyle: {
            background: Colors.red500
        },
    };
};

I can return a random Color object

import Colors from "../UI/Colors";
module.exports = function() {
    return {
        someStyle: {
            background: `Randomly picked object from Color.js file`
        },
    };
};

I'm pretty much clueless on how to achieve this.

0xburned
  • 2,625
  • 8
  • 39
  • 69
  • Possible duplicate - http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array – ggdx Sep 03 '15 at 12:18
  • Is your question on how to get a random color or assigning it to the prop? – BradByte Sep 03 '15 at 12:29
  • @BradBumbalough: Perhaps I wasn't clear enough in my question description. I would like to take a random color from Colors.js and assigning it to the background prop. – 0xburned Sep 03 '15 at 12:36

2 Answers2

0

This is very Easy...

Use Math.random() function of javascript to get a random Value and add that

say background: funtion(){return module.exports[Math.floor((Math.random() * 10) + 1);]

this will return any random value between 1 to 10 as an index. make exports an array and pull that value using this random index and then finally return that value.

Tarandeep Singh
  • 1,322
  • 16
  • 16
0

try this.create a hex random number and return it as background color.i hope you do not want it to be fetched from your file. Edit:check the logic.not sure about syntax

import Colors from "../Colors";
    module.exports = function() {
                      var num=Math.floor((Math.random() * 100) + 1);
                      var color='red'+num;
        return {
            someStyle: {

                         background: colors[color];
            },
        };
    };
shreesha
  • 1,811
  • 2
  • 21
  • 30