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.
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.
1const styles = {
2 style1: {
3 color: "#707cff",
4 fontWeight: "bold",
5 fontSize: 30,
6 },
7 style2: {
8 color: "#3ef059",
9 background: "#000",
10 },
11 style3: {
12 color: "#fff",
13 background: "#c73bed",
14 borderRadius: 6,
15 },
16};
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.
1export const getRandomStyle = () => {
2 var keys = Object.keys(styles);
3 return styles[keys[(keys.length * Math.random()) << 0]];
4};
Import the getRandomStyle
function using the import
statement at the top of your component file as shown below.
1import { getRandomStyle } from "./randomStyle";
Then call the function and store the random style as follows.
1const randomStyle = getRandomStyle();
Using object destructuring, merge the default style with the random style.
1<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.
1import React, { Component } from "react";
2import "./styles.css";
3import { getRandomStyle } from "./randomStyle";
4
5class App extends Component {
6 constructor(props) {
7 super(props);
8
9 this.state = {
10 defaultStyle: {
11 padding: 10,
12 fontSize: 20,
13 },
14 randomStyle: {},
15 };
16
17 this.randomizeStyle = this.randomizeStyle.bind(this);
18 }
19
20 randomizeStyle() {
21 const randomStyle = getRandomStyle();
22 this.setState({ randomStyle });
23 }
24
25 render() {
26 const { defaultStyle, randomStyle } = this.state;
27 return (
28 <div className="App">
29 <span style={{ ...defaultStyle, ...randomStyle }}>Hello World</span>
30 <div class="btn">
31 <button onClick={this.randomizeStyle}>Randomize</button>
32 </div>
33 </div>
34 );
35 }
36}
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.
1const style = Object.assign(defaultStyle, randomStyle);
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".
1import { useState } from "react";
2
3const useRandomStyle = () => {
4 const styles = {
5 style1: {
6 color: "#707cff",
7 fontWeight: "bold",
8 fontSize: 30,
9 },
10 style2: {
11 color: "#3ef059",
12 background: "#000",
13 },
14 style3: {
15 color: "#fff",
16 background: "#c73bed",
17 borderRadius: 6,
18 },
19 };
20
21 const [activeStyle, setActiveStyle] = useState({});
22
23 const getRandomStyle = () => {
24 var keys = Object.keys(styles);
25 return styles[keys[(keys.length * Math.random()) << 0]];
26 };
27
28 const setRandomActiveStyle = () => {
29 const style = getRandomStyle();
30 setActiveStyle(style);
31 };
32
33 return [activeStyle, setRandomActiveStyle];
34};
35
36export 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.
1import React from "react";
2import "./styles.css";
3
4import useRandomStyle from "./useRandomStyle";
5
6export default function App() {
7 const defaultStyle = {
8 padding: 10,
9 fontSize: 20,
10 };
11
12 const [randomStyle, setRandomStyle] = useRandomStyle();
13
14 return (
15 <div className="App">
16 <span style={{ ...defaultStyle, ...randomStyle }}>Hello World</span>
17 <div class="btn">
18 <button onClick={setRandomStyle}>Randomize</button>
19 </div>
20 </div>
21 );
22}
Notice that this implementation is more concise and easier to read than the class component.
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.