What is the best way to incorporate index from a JSX map into a CSS file?

One challenge I am facing is reusing an n dropdown input element in various parts of different applications. This dropdown input element contains options with dropdowns nested within it, and the number of dropdowns can vary. For example:

https://i.sstatic.net/diia5.png

I want to apply styling based on a class

react-select-2-option-[indexOfTheOptionWithDropdown]
. For instance, the dynamic css class for Sydney 333 would be react-select-2-option-2 because it's the second dropdown element in the input field. Similarly, Sydney 333222 would have a dynamic class of react-select-2-option-1.

The problem arises when trying to assign indices to these classes based on the length and position of the dropdown options. The default styles applied by the 'react-select' library are difficult to override, so hardcoding the values seems like a static solution. Is there a more dynamic approach?

In my JSX component, I'm mapping the options along with index numbers. Ideally, I would like to somehow pass this index from the JSX component to the CSS file. Is this feasible? Should I consider using styled CSS components and passing the index to overwrite the CSS, or are there other methods to achieve this?

EDIT: I hardcoded react-select-2-option-4:hover with white background https://i.sstatic.net/161WW.png

default style (options with grey background, no indication of hover) https://i.sstatic.net/sAHOp.png

Answer №1

To define a CSS class name using an index, you can follow the code snippet below.

var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  options[i].className = `react-select-2-option-${i}`;
}

However, this approach may seem unusual. It is recommended to use a variable with common CSS properties and then apply them to the specific style:

var commonCss = { color: 'red', fontWeight: 'bold' };
var specificCss = [{ border: 'solid 1px blue'}];
var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  Object.keys({ ...commonCss, ...specificCss[i] }).forEach(function(key) {
    options[i][key].className = options[key];
  });
}

You can also define a CSS class with common styles and only apply the specific ones as needed:

var specificCss = [{ border: 'solid 1px blue'}];
var options = <list of DOM options like Sydney 333222 and Sydney 333>;
for (var i in options) {
  Object.keys(specificCss[i]).forEach(function(key) {
    options[i][key].className = options[key];
  });
}

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

Using an API to dynamically configure the initial state of a React Checkbox Group

One of the components in my application is called CheckboxGroup, which receives an array of options as a prop and dynamically generates CheckboxInput components. Upon loading the page, I make an API call that returns a list of pre-selected checkboxes (pass ...

Issues with retrieving the output of a function nested within another function through an ajax request

I am attempting to use jQuery to add the results of an ajax call to a paragraph. My goal is to extract the "myResult" variable from the inner getResult function and transfer it to the outer buildParagraph function. Unfortunately, the returned value is und ...

Trouble with line breaks in expandable rows of data grid causing clarity issues

Exploring the expandable rows feature of Clarity datagrid for the first time. I initially thought I could insert any HTML code within the collapsed view to show content. Using VMware's expandable datagrid: However, I am facing an issue where even wh ...

Leverage slot-specific information within the component's script in Vue

In my Vue project, I faced an issue where Component A has a slot that passes an object as slot-scoped to Component B: Template of Component A: <template> <div> <slot :myObject="myObject" /> </div> </template> Template of ...

Having difficulties updating a value in Angular through a function written in HTML- it refuses to update

<select ng-model="currentTimeStartHour" style="width: 33%" ng-change="UpdateTime(this)"> <option ng-repeat="hour in choices" value="{{hour.id}}">{{hour.name}}</option> </select> Somewhere else on the page... {{totalHours}} Whe ...

Utilizing the index of the .map function in conjunction with internal methods

After running my code, I encountered the following error message: Warning: Encountered two children with the same key, `classroom-1278238`. Keys are required to be unique so that components can maintain their identity during updates. Having non-unique keys ...

What steps should I take to ensure my button functions correctly after I have finished writing?

I am attempting to create blog buttons that will input text into a textarea when clicked. However, I am experiencing an issue where the text won't be added if I have already been typing or editing in the textarea before clicking the button. <butto ...

Launching React application from a cloned GitHub repository

I've downloaded a GitHub repository with the code for a ReactJS app into one of my directories, but I'm having trouble running the app on my computer. While I know how to create a new app using create-react-app, I'm unsure how to use the exi ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Discover the versatility of TypeScript by dynamically adding methods to a class!

Are there any examples of dynamically extending a class with a method in TypeScript? I attempted the following: UsersBlocksMyOrders.prototype.myFunc = function():any{ alert('23434'); }; However, the compiler is giving me an error. ...

The error message 404 indicates that the page you are trying to access cannot be found, most likely

Utilizing nextjs dynamic routing, I have implemented a card that, when clicked, redirects to an individual card component based on its id. However, upon clicking the card, it results in a 404 page not found error. The folder structure I am using is located ...

Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separa ...

Changing the primary origins of various elements in MUI Textfield

On the MUI Texfield API, Textfield serves as a simple abstraction incorporating various components: FormControl Input InputLabel FilledInput OutlinedInput Input FormHelperText To customize the styling of the Textfield for any of the above component ...

Ensure jQuery waits until the function has completed execution

Here is the script in question: var d; $(".circle").click(function() { var id = $(this).attr('id'); var MyDiv1 = document.getElementById(id); var name = MyDiv1.innerHTML; $.get("url", function(data){ d=data; }); d=d ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

AngularJS can retrieve the selected value from a select tag

<select ng-model="data.person"> <option value="1" selected="">1 pax</option> <option value="2">2 pax</option> </select> The ng-model above returned "1 pax," but how can I retrieve ...

Differences in behavior between Javascript mousemove and jQuery mousemove in Firefox

I've developed a custom jQuery widget that allows users to draw on a canvas element and record their drawings. However, I encountered an issue in Firefox where the jQuery event wasn't working as expected. Surprisingly, the native JavaScript even ...

Shadows are not being cast by ThreeJS

I'm in the process of creating a simple Three JS application. As I familiarize myself with Three JS, I've been experimenting with different features. Currently, I am working on constructing a scene that includes a floor, an object, and a light so ...

Transitioning from vertical to horizontal orientations in flexbox design

I am looking to achieve the layout shown in this image using flexbox: The image illustrates both portrait and landscape orientations. The left side represents the portrait view while the right side displays the landscape view. My goal is to optimize my H ...

Next.js has shifted away from pre-generating page HTML

I have been working on a Jamstack application using Next.js, and I recently realized that the pages stopped pre-generating the HTML content without me noticing it at first. The pages still load fine, but there is no pre-generated HTML. Even the simplest c ...