A guide to adding and removing classes with a click event in React

Is there a way to dynamically apply and remove CSS classes on click of multiple div elements (rendered by an array of items) in React?

<div 
  onClick={() => { toggleActiveClass(`div${index}`) }}
  className={(activeDiv === `div${index}`) ? "activeFileName" : "inActiveFileName"}  
>
 {item?.name}
</div>

Answer №1

In this scenario, the 'activeFileName' should be added to a div when it is clicked and removed when another div is clicked.

To achieve this functionality, it is necessary to implement indexing while creating the div elements. For example:

<div 
  data-index = {1}
  onClick={(evt) => { setActiveDiv(evt.target.getAttribute("data-index")}}
  className={(activeDiv === 1) ? "activeFileName" : "inActiveFileName"}  
>
  {item?.name}
</div>
<div 
  data-index = {2}
  onClick={(evt) => { setActiveDiv(evt.target.getAttribute("data-index")}}
  className={(activeDiv === 2) ? "activeFileName" : "inActiveFileName"}  
>
  {item?.name}
</div>

It is possible to assign indexes dynamically using a map or other logical operations.

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

Identifying when a fetch operation has completed in vue.js can be accomplished by utilizing promises

Currently, I am facing a dilemma in my Vue.js application. I am making an API call within the created() hook, but there are certain tasks that I need to trigger only after the API call has been completed. The issue is that this API call usually takes aroun ...

Obtaining Prisma arguments by providing the table name as a string

Is there a way to retrieve the query arguments for a Prisma function by only passing the table name? Currently, I know I can obtain the table by providing the table name as a string in the following manner: function (tablename: string) { await prisma.[tab ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

Issue with axios request not being awaited in ReactJs

I have recently developed a ReactJS application where I utilize a singleton class called "ServerMgr" for sending post requests to my server. Initially, I used the JavaScript fetch function which worked perfectly fine. However, I needed to switch to using ...

Creating a forEach statement in an express.js router to handle JSON data

I need help creating an API that will generate a JSON output containing the names extracted from the forEach loop. There are 8 names being processed and I can only use res.send once. See the code snippet below: timeSeries.forEach(data => { res.js ...

What are the steps to successfully implement "Pointermove" event delegation in Safari iOS for parent/child elements?

I've encountered an issue that I'm struggling to find a solution for. My goal is to implement an event delegate using pointermove on a parent container, and I need to be able to detect when the event transitions between a child element and the pa ...

Uncover concealed words within PDF documents

While incorporating PDF.js to display LaTeX typeset PDF files on my website, I encountered an issue. I have concealed specific text in the PDF, but it remains searchable when viewed in Acrobat Reader. Is there a method to search for hidden text using PDF ...

Utilizing information shared between parent and child classes to plot points on a globe

Working on an exciting project to enhance my ReactJS and ThreeJS knowledge, I encountered an issue with passing data from the parent class to functions in the child class. Here's a glimpse of my project: App.js import React, {Component} from 'rea ...

I am excited to incorporate superagent into my TypeScript-enabled React project

Currently, I am attempting to integrate superagent into my TypeScript-ed React project. I have been following a tutorial on TypeScript with React and encountered some difficulties when using superagent for server requests, despite successfully utilizing ma ...

Enable full rotational movement of the Three model using React

Recently, I started using 'three', '@react-three/drei' and '@react-three/fiber' to create a 3D visualization of jaw/teeth. Overall, the outcome is close to my expectations except for two issues that I encountered. One problem ...

Issue with event handling in react-leaflet polygon component

Curious question, my experience involves dynamically rendering Polygons with the help of react-leaflet. The polygons are displaying as expected. However, whatever configurations I apply to eventHandlers seem to have no effect. const highlightFeature = ( ...

What is the best way to link the roll button to a specific video URL?

I am currently working on a project that involves assigning specific videos to 6 roll buttons for continuous play. For instance, I want the first roll button to display a yellow dice and the second button to show a blue dice, and so on. As of now, I have ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Unlocking the request object within a GraphQL resolver with Apollo-Server-Express

My express server is standard and I'm using GraphQL with it const server = express(); server.use('/graphql', bodyParser.json(), graphqlExpress({ schema })); I am wondering how to access the request object within a resolver. Specifically, ...

"PxToRem: A handy PostCSS plugin for converting pixel units

As a beginner in the world of Node.js and post processors for CSS, I recently took the time to install the following tools after going through multiple articles: Node.js (including npm) Gulp PostCSS Pxtorem (a PostCSS plugin for Gulp) My goal is to util ...

Hide a dropdown menu if a user clicks on any item within it

Currently, I am developing a Notification feature for my app similar to the notifications on Facebook. The dropdown opens when I click a button in the header navigation, displaying the notification list with a Link (from react-router) included. The main r ...

What is the process for defining a variable associated with the Google One Tap JavaScript API?

I have been following the documentation on integrating Google One Tap sign-in into my React app using the Google One Tap API. In order to initiate the Google prompt for sign-in, I have included the following code in my component JSX: const handleCredent ...

Can CSS achieve a similar blur effect on a background image as seen in video production?

On my website, I have a photo section that displays random user-submitted images. I am facing the same challenge of fitting images into a frame, similar to how landscape video is adapted for broadcast television when combined with portrait cell phone video ...

Update the text on the button when tasks are in progress in React

I am working on a React project and I need to implement a button that changes its text from Save to Saving... when clicked, and then back to Save once the saving process is complete. My initial approach looks like this: import React from 'react&apos ...

The Material UI Snackbar feature will only display one time and will not reappear

Having issues with the Snackbar component from Material-UI framework. It only shows the first time, then remains closed for subsequent messages. Here's the code used to wrap the Snackbar: import Snackbar from "@material-ui/core/Snackbar"; i ...