React Shuffle – JavaScript Exercise #24

Overview

In this exercise, you will create a React shuffle component a list of items whenever a button is clicked. This exercise will test your knowledge of React state management and event handling.

Instructions for React Shuffle

  1. Create a new React component called ShuffleList.
  2. Inside the ShuffleList component, create an array of items that you want to shuffle. These could be anything from numbers to strings to objects.
  3. Then Render the array of items as an unordered list (<ul>).
  4. Add a button to the component that, when clicked, shuffles the list of items. You can use the Math.random() function to shuffle the array.
  5. Whenever you shuffle the list, update the component’s state to reflect the new order of items.
  6. Finally, Test the component by clicking the button and verifying that the list of items shuffles.

Bonus Requirements

  1. Add a feature that allows the user to sort the list in ascending or descending order by clicking another button.
  2. Create a new component that uses the ShuffleList component and passes in a different set of items to be shuffled.
  3. Use CSS to change the list’s background and the shuffled items’ font color.

Take time to work through the exercise before finalizing your output. I believe that active learning is the most effective way to learn and grow as a developer.

Prepare your tools and begin the React Shuffle exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for React Shuffle exercise

import React, { useState } from 'react';

const ShuffleList = ({ items }) => {
  const [shuffledItems, setShuffledItems] = useState([...items]);

  const shuffleList = () => {
    const shuffled = [...shuffledItems];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    setShuffledItems(shuffled);
  };

  const sortList = (order) => {
    const sorted = [...shuffledItems];
    sorted.sort((a, b) => {
      if (order === 'asc') {
        return a > b ? 1 : -1;
      } else {
        return a < b ? 1 : -1;
      }
    });
    setShuffledItems(sorted);
  };

  return (
    <div>
      <button onClick={shuffleList}>Shuffle</button>
      <button onClick={() => sortList('asc')}>Sort Ascending</button>
      <button onClick={() => sortList('desc')}>Sort Descending</button>
      <ul>
        {shuffledItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

const App = () => {
  const items1 = ['apple', 'banana', 'cherry', 'date'];
  const items2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  return (
    <div>
      <h2>List 1</h2>
      <ShuffleList items={items1} />
      <h2>List 2</h2>
      <ShuffleList items={items2} />
    </div>
  );
};

export default App;

Use cases where shuffling can be useful. Here are a few examples:

  1. Randomized Testing: To test the effectiveness of a product, website, or marketing campaign, researchers perform randomized testing by presenting different versions of the product, website, or marketing campaign to users in a randomized order. They use this approach to assess the effectiveness of each version without the bias of the order in which they were presented.
  2. Games and Quizzes: Developers use shuffling in games, quizzes, and other interactive applications by randomizing questions, answers, or game elements to keep the game engaging and challenging for the user.
  3. Music Playlists: You can use shuffling to create randomized music playlists. This allows users to discover new songs they may not have heard before and keeps the playlist fresh and exciting.
  4. Product Recommendations: E-commerce websites can use shuffling to recommend products to their customers. The website can shuffle the recommended products so that customers see different items each time they visit the website, making it more likely that they will find something they are interested in.
  5. Scientific Studies: In scientific studies, researchers can use shuffling to randomize the order in which they present different treatments or interventions to participants. This helps eliminate any bias that researchers might introduce by presenting the treatments in a specific order.

Conclusion

Shuffling is useful in any situation where a randomized order keeps things fresh, interesting, or unbiased.

People use shuffling as a powerful technique in a variety of contexts, from games and quizzes to scientific studies and e-commerce websites. By randomizing the order of elements, shuffling can help to keep things fresh, engaging, and unbiased. When using shuffling in your applications, be sure to consider the specific context and use case, and use it judiciously to achieve the desired outcome.

Additionally, thank you for taking this JavaScript exercise!

I hope you found this exercise both helpful and enjoyable, and furthermore, that it has deepened your understanding of React development. Additionally, keep practising and experimenting with React, and consequently, you’ll be well on your way to becoming a skilled React developer!

Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top