DEV Community

Ruthramugesh
Ruthramugesh

Posted on

How to generate random colors in SPFx

Introduction:
In this article, we dynamically generate random colors, assign them to a list of items, and apply the same color to duplicate items to improve the user experience in a SharePoint Framework webpart.

The following points will be discussed in detail:

  • Generate a unique color for each item.
  • Apply the Same Colors for Duplicate Items.
  • Highlight only the duplicate items.

These features help users quickly spot repeated entries, reduce confusion, and improve readability. Below is a step-by-step guide to achieving this.

1. Create a SharePoint Framework webpart project
2. Add a new functional react component. Under that add a state variables.

Generate a unique color for each item:

  • We use useState to store random colors for each item.

Image description

  • Random colors are generated using useEffect and stored in the state.

Image description

  • Add the below code in render function, which renders the Items with unique colors.

Image description

  • Below is the output showing unique colors for each item.

Image description

Apply the Same Colors for Duplicate Items:

  • We use useState to store random colors for each item.

Image description

  • Check if the item already has a color stored in userColorMap. If a color already exists for that item, retain the existing color; otherwise, generate a new random color.

Image description

  • Render duplicate items with the same colors.

Image description

  • Below is the output showing the same color applied to duplicate items.

Image description

Highlight only the duplicate items:

  • We use useState to store the count and color of duplicate items.

Image description

  • We use the userCountMap variable to count how many times an item appears. If an item appears more than once, We store its frequency and the generated random color in the state.

Image description

  • Render duplicate items by highlighting them with the same color, ensuring that each group of duplicates has a unique color.

Image description

  • Below is the output highlighting duplicate group items.

Image description

Conclusion :
The code generates random colors, assigns a unique color to each item, and ensures that the same item retains the same color throughout the list. Additionally, if an item appears more than once, it is highlighted using the same assigned color for consistency.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay