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.
- Random colors are generated using useEffect and stored in the state.
- Add the below code in render function, which renders the Items with unique colors.
- Below is the output showing unique colors for each item.
Apply the Same Colors for Duplicate Items:
- We use useState to store random colors for each item.
- 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.
- Render duplicate items with the same colors.
- Below is the output showing the same color applied to duplicate items.
Highlight only the duplicate items:
- We use useState to store the count and color of duplicate items.
- 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.
- Render duplicate items by highlighting them with the same color, ensuring that each group of duplicates has a unique color.
- Below is the output highlighting duplicate group items.
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.
Top comments (0)