Author avatar

Gaurav Singhal

Randomly Assigning Object Props from Files to Inline-CSS

Gaurav Singhal

  • Sep 3, 2020
  • 6 Min read
  • 31 Views
  • Sep 3, 2020
  • 6 Min read
  • 31 Views
Web Development
Front End Web Development
Client-side Frameworks
React

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const styles = {
  style1: {
    color: "#707cff",
    fontWeight: "bold",
    fontSize: 30,
  },
  style2: {
    color: "#3ef059",
    background: "#000",
  },
  style3: {
    color: "#fff",
    background: "#c73bed",
    borderRadius: 6,
  },
};
js

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.

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

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.

1
import { getRandomStyle } from "./randomStyle";
jsx

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

1
const randomStyle = getRandomStyle();
jsx

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

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

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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>
    );
  }
}
jsx

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.

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

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".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
js

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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>
  );
}
jsx

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.

0