React Shuffle - JavaScript Exercise #24

React Shuffle - JavaScript Exercise #24

Build a React component that shuffles a list of items

ยท

4 min read

Overview

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

Instructions

  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. 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 the list is shuffled, update the component's state to reflect the new order of items.

  6. Test the component by clicking the button and verifying that the list of items is shuffled.

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 add some style to the component, such as changing the background color of the list or the font color of the shuffled items.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into 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 the 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, randomized testing can be performed where different versions of the product, website or marketing campaign can be presented to the users in a randomized order. By doing this, the effectiveness of each version can be assessed without the bias of the order in which they were presented.

  2. Games and Quizzes: Shuffling can be used in games, quizzes, and other interactive applications where questions, answers, or game elements are randomized to keep the game engaging and challenging for the user.

  3. Music Playlists: Shuffling can be used 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, shuffling can be used to randomize the order in which different treatments or interventions are presented to participants. This helps to eliminate any bias that might be introduced if the treatments were presented in a specific order.

Overall, shuffling can be useful in any situation where a randomized order is required to keep things fresh, interesting, or unbiased.

Shuffling is a powerful technique that can be used 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.

Thanks for taking this JavaScript exercise!

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

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย