Switching the class from "untoggled" items to the selected item in React

Recently, I developed a toggle component known as Accordion. Within this component, I am iterating through an array of objects and displaying them in the following format:

{object.map((o) => (
   <Accordion key={o.id} title={o.question} className="item">
     <div className="text"> { o.answer } <div/>
   </Accordion>
))}

This results in the rendering of something similar to the following:

> Question 1
> Question 2
> Question 3

The functionality of toggling each question to reveal its answer is working smoothly, thanks to the utilization of hooks.

However, I aim to enhance the user experience by adjusting the opacity of all untoggled elements when one question is expanded. For instance, opening question 2 should highlight it while dimming out or reducing the opacity of question 1 and question 3. Although I could achieve this effect using :hover in CSS, it only triggers on hover events.

In essence, I need to dynamically modify the styling to emphasize the selected item and de-emphasize others. Yet, I am unsure how to implement this practically. Any guidance would be greatly appreciated as I suspect I might be overlooking a simple solution.

const Accordion = ({ title, children, opened = false }) => {
  const [show, setShow] = useState(opened);
  const rotation = classnames('icon', {
    'rotate': show,
  });
  const content = classnames('contents', {
    'closed': !show,
  });

  useEffect(() => {
    setShow(opened);
  }, [opened]);

  const toggle = useCallback(() => {
    setShow(!show);
  }, [show]);

  return (
      <div className='titleContainer' onClick={toggle}>
        <div className={rotations}>
          <i className='icon' />
        </div>
        <h5 className='title'>{title}</h5>
      </div>
      <div className={content}>{children}</div>
  );
};

Answer №1

After careful consideration, I have grasped your message and believe this to be the solution:

const determineColor = (index, activeIndex) => {
    if (activeIndex !== null && activeIndex !== index) {
      return "rgba(0,0,0,0.1)";
    } else return "rgba(0,0,0,1)";
  };

See the working solution in action: https://codesandbox.io/s/cocky-hellman-fxrmc

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

Tips for maintaining grid width when columns are rearranged in the column menu

Is it possible to stop jqgrid from changing its width to full screen after column selection? I attempted the code below, following guidance from How to change column name in column chooser pop up in jqgrid? My aim was to create a column switcher function ...

Failure to Connect HTML with Stylesheet

Feeling a bit lost here. I've been attempting to connect my homepage to my stylesheet, but no matter how often I refresh the page, it just won't recognize the link. I'm diligently following the instructions from the guide I have, copying and ...

Adjust the message hues upon form submission with Ajax

Can anyone provide assistance? I am in need of a functional form for sending emails. <form enctype="multipart/form-data" role="form" id="form" method="post" action="handler.php"> <div class="form-row"> <div class="form-g ...

Fading text that gradually vanishes depending on the viewport width... with ellipses!

I currently have a two-item unordered list positioned absolutely to the top right of the viewport. <header id="top-bar"> <ul> <li> <a href="#">David Bowie</a> </li> <li> ...

How to customize the active color of the navigation pills in Bootstrap 4

I want to customize the background color of each pill, but I also want a faded version of that custom color with an active color matching the full color of the corresponding pill. pill one > faded red pill two > faded blue pill three > faded black When ...

Is there a way for me to update a Link To containing a parameter by using history.push with a parameter inside a table cell?

Hey there! I'm working on some code and wondering if it's doable to replace the Link To with a history.push, including the following parameter, like so: <TableCell style={{width: '10%'}}> <Link to={`/run-id/${item.run_ ...

What is the process for bringing in a reducer from createSlice into store.js using @reduxjs/toolkit?

Can someone please provide guidance on how to correctly export the todos reducer from todosSlice using createSlice @reduxjs/toolkit, and then import it into the store using configureStore? Below is my todosSlice file : //todosSlice file import {cr ...

new cookies are created without human intervention

Working on a project in Next.js and using the react-cookie npm package for managing sessions. I am creating a cookie with the key name "token" and assigning the token value as its value. However, an issue has arisen related to cookies where multiple cooki ...

unexpected alteration of text sizing in mathjax within reveal.js presentations

Something strange is happening with the font size in my slides. The code for each slide is the same, but there is an unexpected change between the 3rd and 4th slide. I cannot figure out what is causing this discrepancy. Oddly enough, when I remove the tit ...

Trigger a fixed bottom bar animation upon hover

I have a bar fixed to the bottom of the browser that I want to hide by default. When a user hovers over it, I want the bar to be displayed until they move their cursor away. <!doctype html> <html> <head> <meta charset="utf-8"> &l ...

Challenge with CSS Layering

I'm currently experiencing some issues with layering on my website. The problem at hand is that visitors are unable to interact with links within the div layers for some unknown reason. They can't click on the sidebar images or highlight text. I& ...

Encountering a problem with the React version. Upgrading to a newer version

I've been facing issues with installing the latest version of react. Even after trying different methods like appending @ to specify a particular version or completely uninstalling nodejs, it still doesn't work. npm react --version 6.14.15 When ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

an online platform design

I am currently working on building a webpage, but I am facing some issues with the layout. Specifically, I am unable to make the div automatically adjust its size (particularly the height). Here is the code that demonstrates the problem: <!DOCTYPE html ...

Error: The constructor for JsSHA is not valid for the TOTP generator

Attempting to create a TOTP generator similar to Google's timed-based authenticator using the React framework. I am utilizing the bellstrand module for TOTP generation, but I am encountering issues when trying to import it into my React code. Here is ...

Tips on preventing repeated data fetching logic in Next.js App Routes

I'm currently developing a project with Next.js 13's latest App Routes feature and I'm trying to figure out how to prevent repeating data fetching logic in my metadata generation function and the actual page component. /[slug]/page.tsx expo ...

Tips for preventing FormLabel components from turning blue when a radio button is selected

Currently, I am working on a Reactjs project that utilizes Material Ui components. In this project, I am tasked with creating a form to generate a new event where users can select the event location type from three options - In-Person, Hybrid, and Virtual ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

Turn off hover functionality for mobile and tablet devices

Is there a way to prevent hover effects on mobile and tablet devices for an SVG file used in the img tag? scss file: .menu-link:hover { img { filter: invert(40%) sepia(90%) saturate(2460%) hue-rotate(204deg) brightness(93%) contrast(93%); } .side ...

Obtain access to the child canvas element within the parent component

I'm currently working on an app that allows users to sign with a digital pointer. As part of the project, I have integrated react-canvas-signature. My next task is to capture the signature from the canvas and display it in a popup. According to thei ...