Styling Dropdown Options Based on Conditions in React

In my current project, I am attempting to modify the className of selected items within a mapped array using another array (this.props.notPressAble). The reason for this is because I want certain objects in the array to have a different CSS style.

handleOptions = () =>{
    let array = this.props.options.map((option, i) => 
    <a 
    key={i} 
    className={classes.dropdownoptions}>
    {option}</a>)

    for(let x = 0; x < this.props.options.length; x++)
    {
        if(this.props.notPressAble !== undefined)
        {
            for(let y = 0; y < this.props.notPressAble.length; y++)
            {
                if(x == this.props.notPressAble[y])
                {
                    array[x].props.className = classes.dropdownoptionsnotpressable
                }
            }
        }
    }

    return array
}

Below is where I apply the class to help readers better understand my issue:

 <SideBarContainers name="Planning" notPressAble={[0, 6, 11]}
 options={[
     "Activities:",
     "+ New Activity",
     "Show All Open",
     "Show Delayed",
     "Show All Closed",
     "Show Categorized All",
     "To do:",
     "+ New To Do",
     "Show All Open",
     "Show All Closed",
     "Show Categorized All",
     "Personal planning:",
     "+ New Post",
     "Show Simple All"

]} />

The issue I'm facing is that array[x].props.className is a readOnly value and cannot be altered. Is there an alternative method to achieve this?

Answer №1

Why do you insist on using for loops to iterate through options and then notPressAble? You could simply utilize the includes function to determine which class to use.

handleOptions = () => {
    let array = this.props.options.map((option, i) => {
      const cls = this.props.notPressAble.includes(i) ? classes.dropdownoptionsnotpressable : classes.dropdownoptions
      return (
        <a key={i} className={cls}>
          {option}
        </a>
      )
    });

    return array;
  };

If you still prefer to stick with your current code, then you must clone the element you wish to modify and then apply the changes as shown below.

//array[x].props.className = classes.dropdownoptionsnotpressable
array[x] = React.cloneElement(array[x], {className: classes.dropdownoptionsnotpressable});

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

Loading templates (partials) in Angular.js on the fly

Is there a way to dynamically load templates into an Angular app based on a parameter within a ng-foreach loop? <body ng-app="MyApp" ng-controller="ExampleController as example"> <div ng-repeat="item in example.items" class="someClass" ng-swi ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Ensure modifications to a variable are restricted within an if statement

I am struggling to find a way to globally change a variable within an if statement and ensure that the modifications persist. User input: !modify Bye var X = "Hello" if (msg.content.includes ('!modify')) { X = msg.content.replace('!modi ...

Error in typing on a prismic application utilizing a ContentRelationshipField

I am facing a type error in my Prismic Next.js application that I am struggling to resolve. While the app functions properly, I keep encountering type errors like the following: The property 'data' does not exist on the type 'ContentRelati ...

Issue with loading controllers in route files [Node.js]

I've encountered an issue while trying to include a user controller into my routes for a node js app. Everything was working fine until suddenly it started throwing an error message. I've thoroughly checked the code for any potential issues but s ...

What methods can be employed to stop tests from being included in rollup bundles?

I am currently in the process of creating a react component package and I would like to know how to prevent my tests folder from being included in the dist file that is generated by rollup. After running rollup -c, my directory structure looks like this: ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

Avoiding code duplication in Angular: tips for optimizing functions

Is there a way to avoid repeating the same for loop for a second variable and use only one? I'm trying to apply the "Don't repeat yourself" method here. Should I consider using an array? JS: var app=angular.module('xpCalc', []); app.c ...

Issue with Pure Javascript FormData upload involving files and data not successfully processing on PHP end

My file upload form follows the standard structure: <form id="attachform" enctype="multipart/form-data" action="/app/upload.php" method="POST" target="attachments"> <!-- MAX_FILE_SIZE must precede the file input field --> <i ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

The CSS keyframe for mobile devices initiates from 100% and then proceeds to animate

Having some trouble with CSS animations on mobile devices. The animation works perfectly fine on desktop, but on mobile, it seems to display the final 100% keyframe first before animating from 0%. I've tried adding the initial style directly to the cl ...

Tips for shifting a fabricjs element generated within a nextjs useState hook?

I encountered an issue where creating a fabric canvas in a useEffect() function prevents me from moving the added images. However, if I create the canvas elsewhere (even though it may be subject to useState asynchrony issues), I am able to move the image ...

AngularJS: resolving route dependencies

I have a variable $scope.question that contains all the questions for the page. My goal is to loop through the questions page by page. To achieve this, I created a function called questionsCtrl and I am calling this function in the config while setting up ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

What is the process by which browsers manage AJAX requests when they are made across

I have encountered an issue that is puzzling to me, and I suspect it might be due to my misunderstanding of how the browser handles AJAX requests. Just for context, I am using Codeigniter on an Apache server and triggering AJAX requests with jQuery. The b ...

Utilize React to access an external variable that has been declared outside of the root component

My React application is bundled and loaded into an HTML file using a script tag. I need to pass some initial data to the application, and I am looking for suggestions on how to define this data either in the HTML itself or in previously loaded JavaScript f ...

Challenge with the Bootstrap 3 grid structure involving nesting

On my .aspx page, I have the code snippet below: .cDiv { background-color: gray; } .tColor { background-color:yellow; } .tColor2 { background-color:blue; } <div class="container"> <div class="row"> <div class="col-sm-9 tColor" ...

What is the best way to connect an external JSON file to an Angular controller?

As I embark on my first Angular JS project, I find myself in need of exporting a JSON array from my controller to an external JSON file. Here is the snippet from my controller containing the JSON data: Fantacalcio.controller('fantacalcioController&ap ...

Retrieve Data with Conditions using the Json Placeholder API

I have been working on integrating my posts with the user table using the Json PlaceHolder API and nextJS for the past couple of days. Despite trying different approaches, I haven't been able to figure out the right logic yet. Any guidance or assistan ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...