Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Randomly Assigning Object Props from Files to Inline-CSS

Sep 3, 2020 • 6 Minute Read

Introduction

Random outcome generation is an everyday use case when it comes to developing browser-based apps or games using React. It could involve rolling a die, shuffling a deck of cards, or any other similar game.

In this guide, you will learn how to randomly generate a value of a property in an object and assign it as a prop in a React component.

Getting a Random Key From An Object

Get started by creating a styles object in the randomStyles.js file. This styles object will have different style objects that will be chosen at random.

      const styles = {
  style1: {
    color: "#707cff",
    fontWeight: "bold",
    fontSize: 30,
  },
  style2: {
    color: "#3ef059",
    background: "#000",
  },
  style3: {
    color: "#fff",
    background: "#c73bed",
    borderRadius: 6,
  },
};
    

Next, create an export function called getRandomStyle that will select a random property from the styles object. Adding the export keyword before the function name will allow the function to be imported and accessed by other files in your codebase.

      export const getRandomStyle = () => {
  var keys = Object.keys(styles);
  return styles[keys[(keys.length * Math.random()) << 0]];
};
    

Assigning an Object To a Style Prop

Import the getRandomStyle function using the import statement at the top of your component file as shown below.

      import { getRandomStyle } from "./randomStyle";
    

Then call the function and store the random style as follows.

      const randomStyle = getRandomStyle();
    

Using object destructuring, merge the default style with the random style.

      <span style={{ ...defaultStyle, ...randomStyle }}>Hello World</span>
    

Now that you have a clear idea of how to get a random style object using the function, create a React component and use the randomStyle() function.

You can store the default style props in the component's state, which will be applied immediately when the component mounts on the page. Create a button that will trigger the randomizeStyle() method and set the new random style in the state.

      import React, { Component } from "react";
import "./styles.css";
import { getRandomStyle } from "./randomStyle";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      defaultStyle: {
        padding: 10,
        fontSize: 20,
      },
      randomStyle: {},
    };

    this.randomizeStyle = this.randomizeStyle.bind(this);
  }

  randomizeStyle() {
    const randomStyle = getRandomStyle();
    this.setState({ randomStyle });
  }

  render() {
    const { defaultStyle, randomStyle } = this.state;
    return (
      <div className="App">
        <span style={{ ...defaultStyle, ...randomStyle }}>Hello World</span>
        <div class="btn">
          <button onClick={this.randomizeStyle}>Randomize</button>
        </div>
      </div>
    );
  }
}
    

That's it. All the logic for randomly fetching the value was written in a separate file, so in the React component, all you had to do was use the function and assign the value to props.

If you don't want to use object destructuring, you can use the Object.assign() function to merge the defaultStyle and randomStyle objects.

      const style = Object.assign(defaultStyle, randomStyle);
    

Hook-based Implementation

Now it's time to take a look at an alternative solution using React hooks. Similar to the class component, here as well you will generate a random style outside of the component file. But in this case, it will be in the form of a custom hook.

Create a function called useRandomStyle, which will generate the style and return the function to generate a new random style. Note that since it is a custom hook, it's a convention to prefix the function name with "use" followed by the name suggesting the purpose of the hook—in this case, "RandomStyle".

      import { useState } from "react";

const useRandomStyle = () => {
  const styles = {
    style1: {
      color: "#707cff",
      fontWeight: "bold",
      fontSize: 30,
    },
    style2: {
      color: "#3ef059",
      background: "#000",
    },
    style3: {
      color: "#fff",
      background: "#c73bed",
      borderRadius: 6,
    },
  };

  const [activeStyle, setActiveStyle] = useState({});

  const getRandomStyle = () => {
    var keys = Object.keys(styles);
    return styles[keys[(keys.length * Math.random()) << 0]];
  };

  const setRandomActiveStyle = () => {
    const style = getRandomStyle();
    setActiveStyle(style);
  };

  return [activeStyle, setRandomActiveStyle];
};

export default useRandomStyle;
    

A custom hook must return an array, which should include the value and a function that can change that value; in this case, the value is the style object and the function is setRandomActiveStyle.

Then, inside the App component, call the useRandomStyle function, as shown below.

      import React from "react";
import "./styles.css";

import useRandomStyle from "./useRandomStyle";

export default function App() {
  const defaultStyle = {
    padding: 10,
    fontSize: 20,
  };

  const [randomStyle, setRandomStyle] = useRandomStyle();

  return (
    <div className="App">
      <span style={{ ...defaultStyle, ...randomStyle }}>Hello World</span>
      <div class="btn">
        <button onClick={setRandomStyle}>Randomize</button>
      </div>
    </div>
  );
}
    

Notice that this implementation is more concise and easier to read than the class component.

Conclusion

Randomizing outcomes can seem daunting at first, but it is just a matter of using the correct method and implementation logic. Fun fact: a random number or outcome generated with an algorithm is not truly random. Because numbers generated using algorithmic functions cannot be random in a real sense, they are called pseudo-random numbers.

That's it from this guide. Keep exploring random numbers and their use cases.