What is the best way to transform a ternary operation into an Enum Map with custom properties

I'm faced with the challenge of styling a button based on the selection made in a select box. The code snippet I have currently is as follows:

const buttonStyles = {
    backgroundColor: buttonStyle === 'Black' ? colors.interactiveForegroundSecondary : buttonStyle === 'Green' ? colors.backgroundInverseSecondary : buttonStyle === 'White' ? colors.backgroundPrimary : buttonStyle === 'Lime Green' ? colors.graphTertiary : '',
    color: buttonStyle === 'Black' ? colors.textInversePrimary : buttonStyle === 'Green' ? colors.textInversePrimary : buttonStyle === 'White' ? colors.interactiveForegroundSecondary : buttonStyle === 'Lime Green' ? colors.backgroundInverseSecondary : '',
    "&:hover": {
      background: buttonStyle === 'Black' ? colors.backgroundInversePrimary : buttonStyle === 'Green' ? colors.accentPrimary : buttonStyle === 'White' ? colors.errorBackground : buttonStyle === 'Lime Green' ? colors.backgroundInverseSecondary : '',
      color: buttonStyle === 'Lime Green' ? colors.graphTertiary : ''
    },
  } as CrateStyleObject

My aim is to refactor this code into an Enum map in typescript. I have started with the following approach:

enum ButtonBackground {
  Black = colors.interactiveForegroundSecondary,
  Green = colors.backgroundInverseSecondary,
  White = colors.backgroundPrimary,
  Lime Green = colors.graphTertiary ,
}
const submitBackground = (Object.keys(ButtonBackground) as (keyof typeof ButtonBackground)[]).map(
  (key, index) => {
    console.log(key);
    return ButtonBackground[key] + index;
  },
);

Then I plan on applying it to the component as shown below: 

<Button
  style={
    buttonStyles
  }
  type="submit">
{text}
</Button/>

However, I'm facing a challenge in assigning

colors.interactiveForegroundSecondary
to one of the keys due to it not being a string. Additionally, I need the background color and text color of the button to change based on the selected value. Would creating separate Enums for each background color, text color, hover background color, and hover text color be the solution to this issue?

Answer №1

In my opinion, it would be beneficial to establish a distinct enum for ButtonBackgroundColor, ButtonColor, ButtonBackgroundColorOnHover, and ButtonColorOnHover.

I find it puzzling why there is an attempt to loop through the enum when the goal is simply to adjust the buttonStyles based on the value of the buttonStyle variable. Here's how I would approach it:

const buttonStyle = 'Lime Green' // For instance

// We must eliminate spaces since enums cannot have multiple words
const buttonStyleWithNoWhitespace = buttonStyle.replace(/\s/g, '')

enum ButtonBackground {
  Black = colors.interactiveForegroundSecondary,
  Green = colors.backgroundInverseSecondary,
  White = colors.backgroundPrimary,
  LimeGreen = colors.graphTertiary,
}

enum ButtonColor {
  Black = colors.backgroundInversePrimary,
  Green = colors.accentPrimary,
  White = colors.errorBackground,
  LimeGreen = colors.backgroundInverseSecondary,
}

enum ButtonBackgroundOnHover {
  Black = colors.backgroundInversePrimary,
  Green = colors.accentPrimary,
  White = colors.errorBackground,
  LimeGreen = colors.backgroundInverseSecondary,
}

enum ButtonColorOnHover {
  Black = '',
  Green = '',
  White = '',
  LimeGreen = colors.graphTertiary,
}

const buttonStyles = {
    backgroundColor: ButtonBackground[buttonStyle as keyof typeof ButtonBackground],
    color: ButtonColor[buttonStyle as keyof typeof ButtonColor],
    "&:hover": {
        background: ButtonBackgroundOnHover[buttonStyle as keyof typeof ButtonBackgroundOnHover],
        color: ButtonColorOnHover[buttonStyle as keyof typeof ButtonColorOnHover]
    }
} as CreateStyleObject

<Button 
    style={buttonStyles} 
    type="submit">
    {text}
</Button/>

The as keyof typeof Enum seems to overly complicate the usage of enums, when a simple object could suffice. However, there might be specific reasons that necessitate the use of enums.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below: @Component({ selector: 'item-selector&apos ...

The functionality of my script relies on the presence of an alert function within it

My code seems to only work when I include an alert function in it. I'm trying to make my div scroll to the bottom. I've done some research, but for some reason, the script doesn't run without an alert function. $(document).ready(function ...

Unexpected behavior: getElementById returning URL instead of element

I created a function that accepts a thumbnail path as an argument, waits for the bootstrap modal to open, and then assigns the correct path to the thumbnail href attribute within the modal. However, when I use console.log with the element(el), it displays ...

Discover the power of React Meteor, where reactive props and inner state work together

I am working with a component that utilizes the draft-js library for text editing. import React, { Component } from 'react' import { EditorState, convertToRaw } from 'draft-js' import { Editor } from 'react-draft-wysiwyg' imp ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...

Can you find a method to retrieve the current page on a dashTable?

I am facing a challenge with my dashtable which contains over 5000 records and is paginated to load faster. However, I have noticed that when I set the page size to 5000, the loading speed decreases significantly. I have implemented a function that retriev ...

Using the promise expression in AngularJS's ng-show

I have a scenario where I am using ng-show with an expression that evaluates to a promise which then resolves to a boolean. This setup is resulting in a 10 digest iterations overflow error. For reference, you can view the code snippet at http://plnkr.co/e ...

Acquiring the parent object (a group) from the children in Three.js

In the scenario I have created, there are multiple groups of objects (Object3Ds) and I have established a mechanism for clicking or hovering over them to trigger specific actions. However, when using the raycaster to identify the objects under the cursor, ...

CSS - Struggling to identify the source of unwanted horizontal scrolling?

Recently, I've been attempting to make adjustments to a responsive website that utilizes media queries. Despite my efforts, whenever the site is viewed on a mobile-sized screen, it consistently requires horizontal scrolling regardless of the screen&a ...

Tailwind's unique approach to custom @font-faces allows for

Recently, I've been working on a project with Tailwind CSS. I encountered an issue when trying to implement a custom font using @font-face. Despite placing the font file in public/assets/font directory, it still doesn't seem to load properly. Her ...

Command for controlling volume in DiscordJS

Despite my efforts, I am struggling to write a command that successfully changes the volume of the music being played. Every time the player and resource variables in the volume() function are empty while the bot is playing the song. What can I do to resol ...

Encountered an unexpected token error while using Jest with TypeScript, expecting a semicolon instead

I have been struggling to configure jest for use with typescript and despite trying several solutions, I am still facing issues. The error SyntaxError: Unexpected token, expected ";" keeps popping up, indicating that the configuration may not be compatible ...

Effortlessly Styling Children Elements in Emotion JS When Parent Element is Hovered

This particular query seems to have been posed and resolved in various ways, but the solutions I've come across either do not pertain to Emotion or the responses related to Emotion haven't yielded results for me. I am currently using @emtion/[ema ...

Selenium is unable to engage with elements within an accordion section

I have been grappling with a challenge in setting up an automation test for a website. I am able to successfully log in and reach the dashboard. However, I encounter a roadblock when attempting to click on a module from a sidebar menu as Selenium seems una ...

Extract features from React Native components

I am having trouble exporting a function to an actions.js file. The code below is the one that works: export default class HomeScreen extends Component { constructor(props) { super(props); this.state = { visible: false } } onOpen ...

Playing a game of rock, paper, scissors with two players using JavaScript

Hello! I am a beginner in JavaScript and I am trying to create a simple rock, paper, scissors game. However, when I run the code, I receive two prompt messages and an error saying 'TypeError: playerOneChoice is not a function'. What mistake did I ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

Troubleshooting issue: Bootstrap mixins not functioning properly due to LESS nesting

Recently I've been experimenting with Bootstrap and LESS, attempting the following: LESS: .class1 { .jumbotron; div { .container(); color: white; } } Here is the relevant part of the HTML code: <div class="class1"> <div> ...

Receiving 'Module not found' error in Typings on specific machines within the same project. Any suggestions on how to troubleshoot this issue?

I have a project cloned on two separate machines, each running VS2015 with Typings 1.8.6 installed. One machine is running the Enterprise version while the other has the Professional version, although I don't think that should make a difference. Inte ...

What is the best method for eliminating the gap between div elements in CSS?

I am in the process of creating a simple website to brush up on my basic HTML and CSS skills. Utilizing Dreamweaver CS6, I aim to master every aspect of web design the correct way. While exploring how to position div elements, specifically using margins fo ...