React - dynamically assign className based on loop data values

0 votes
34 views
added Jan 26 in React by lcjr First Warrant Officer (11,850 points)
import React from 'react';

const LoopData = () => {
  // Dummy data for the loop
  const prompts = [
    {
      title: 'prompt 1',
      category: 'dummy listings',
      description: 'Lorem ipsum dolor sit amet 1 ipsum dolor sit amet 1',
    },
    {
      title: 'prompt 2',
      category: 'odd stuffs',
      description: 'Lorem ipsum dolor sit amet 2 ipsum dolor',
    },
    {
      title: 'prompt 3',
      category: 'cool stuffs',
      description: 'Lorem ipsum dolor sit amet 3 psum dolor sit a',
    },
    {
      title: 'prompt 4',
      category: 'dummy listings',
      description: 'Lorem ipsum dolor sit amet 4 m dolor sit ame',
    },
    {
      title: 'prompt 5',
      category: 'cool stuffs',
      description: 'Lorem ipsum dolor sit amet 5 m dolor s',
    },
  ];

  // Function to get the category number
  const getCategoryNumber = category => {
    const categoryMap = {
      'dummy listings': 1,
      'odd stuffs': 2,
      'cool stuffs': 3,
      // Add more categories as needed
    };

    return categoryMap[category] || 0;
  };

  return (
    <div className="prompt-group">
      {prompts.map((prompt, index) => (
        <div
          key={index}
          className={`prompt-box cat${getCategoryNumber(prompt.category)}`}
        >
          <div className="prompt-title">{prompt.title}</div>
          <div className="prompt-desc">{prompt.description}</div>
        </div>
      ))}
    </div>
  );
};

export default LoopData;

 

In the provided code above, the data of prompt.category refers to the category of each item in the prompts array. In this case, the categories are strings like 'dummy listings', 'odd stuffs', and 'cool stuffs'. The getCategoryNumber function is used to map these category strings to numerical values.

Here's the breakdown:

  • The prompts array contains objects, each with properties like title, category, and description.
  • The getCategoryNumber function takes a category string as an argument and maps it to a numerical value using the categoryMap object.
  • The categoryMap object assigns a numerical value to each category string. For example, 'dummy listings' is assigned the value 1, 'odd stuffs' is assigned 2, and 'cool stuffs' is assigned 3.

So, when the code uses getCategoryNumber(prompt.category), it is retrieving the numerical value associated with the category string of the current prompt object in the loop. The resulting class name for the div element is then constructed with the format cat${getCategoryNumber(prompt.category)}, and this class is applied to the rendered prompt box. This class likely affects the styling or appearance of the prompt based on its category.

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...