When a user clicks on a specific accordion, the icon for all accordions under mui control will change

My current task involves mapping over an array of data to render multiple controlled accordions. Each accordion should open/close individually upon clicking, but I'm facing an issue where the icons for all accordions are changing when I interact with one. I understand that this is happening because of how I've mapped the components, but I'm unsure of how to assign a unique id to each accordion's icon element. Here is a snippet of my code:

import * as React from 'react';
import Accordion from '@mui/material/Accordion';
import AccordionDetails from '@mui/material/AccordionDetails';
import AccordionSummary from '@mui/material/AccordionSummary';
import Typography from '@mui/material/Typography';
import ControlPointIcon from '@mui/icons-material/ControlPoint';
import RemoveCircleOutlineIcon from '@mui/icons-material/RemoveCircleOutline';

const data = [{left: "general settings", right:"this is an accoridon", text :"blabla", id:"pannel-1"}, {left:"users", "right": "you'r not an user", text:"allela eegf aa ", id:"pannel-2"}]

export default function ControlledAccordions() {
  const [expanded, setExpanded] = React.useState<string | false>(false);
  const expandicon = expanded ? <RemoveCircleOutlineIcon /> : <ControlPointIcon />

  const handleChange =
    (panel: string) => (event: React.SyntheticEvent, isExpanded: boolean) => {
      setExpanded(isExpanded ? panel : false);
    };

  return (
    <div>
     {data.map((item) => 
      <Accordion expanded={expanded === item?.id} onChange={handleChange(item.id)}>
      <AccordionSummary
        expandIcon={expandicon}
        id={item.id}
      >
        <Typography sx={{ width: '33%', flexShrink: 0 }}>
         {item.left}
        </Typography>
        <Typography sx={{ color: 'text.secondary' }}>{item.right}</Typography>
      </AccordionSummary>
      <AccordionDetails>
        <Typography>
         {item.text}
        </Typography>
      </AccordionDetails>
    </Accordion>)}
     
   
    </div>
  );
}

I am seeking guidance on how to uniquely identify and control each accordion icon.

Answer №1

To customize the AccordionSummary component with the same logic as the expanded attribute of Accordion, you can make the following changes:

<AccordionSummary
  expandIcon={
    expanded === item?.id ? (
      <RemoveCircleOutlineIcon />
    ) : (
      <ControlPointIcon />
    )
  }
  id={item.id}
>
  /*...*/
</AccordionSummary>

You can then eliminate the use of the expandicon variable.

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 sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

Executing a function within a React component's render method

There's a specific code line I'm working with: <td>{device.ID}</td> My goal is to display the device type using the ID number and then call a function based on it. I attempted the following method after finding guidance here: < ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

What is a more effective method for updating a component by utilizing both state and props for rendering?

I am new to Next.js and ReactJS, and I recently encountered a situation where I needed to create a component that would render different child components within the parent component based on a click event in the DOM element to change its state. My initial ...

Establishing a default value for Image src within next.js would ensure that a placeholder image

I have been struggling to set a default value for the image src in the Image component within my next.js project. I have not been able to find any options to handle the scenario where the server responds with a status code of 400. Currently, I am receiving ...

Exploring the world of end-to-end testing for playwright. How to handle oauth2 and email-passwordless authentication in your testing

As I delve into e2e testing with Playwright, I've encountered a challenge. The application I need to test can only be accessed through Github OAuth or email authentication links, managed by next-auth in a NextJS project. I'm unsure how to approa ...

Setting Default Values for Multi-select in React-select Async

What is the method for setting default selected values in React-select Async Multi-select? Below is a sample form utilizing react-hook-form and react-select: <form onSubmit={handleSubmit(onSubmit)} > {updateError && renderError(updateError)} ...

I'm curious if there is a method in Next.js to dynamically replace all `<a>` tags within nested components in order to prevent full page refreshes

Our client requires the use of a React component library that offers various layout components such as Header/Footer elements and Navigation menus. However, only the href string value can be passed for navigation items, preventing any manipulation during r ...

Guide to creating a custom wrapper for a Material UI component with React JS

I am utilizing the Material UI next library for my project and currently working with the List component. Due to the beta version of the library, some parameter names are subject to change. To prevent any future issues, I have decided to create a wrapper a ...

Simplify Chart.JS's file size by optimizing select chart types

When I was exploring the documentation for Chart.JS on their website, specifically at the Quick start section, I came across a note that mentioned importing the package as import Chart from 'chart.js/auto' to get access to all the features. My i ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...

React-Native: Issue with animation not displaying on RefreshControl when used on ScrollView with nested View

I'm fairly new to React Native and I've been working on implementing a refreshable list of contacts. However, I seem to be encountering an issue where the pull-down animation is not working as expected. It's likely that I missed something in ...

The Axios and TypeScript promise rejection error is displaying an unknown type- cannot identify

Currently, I am encountering an issue where I am unable to utilize a returned error from a promise rejection due to its lack of typability with Typescript. For instance, in the scenario where a signup request fails because the username is already taken, I ...

An in-depth guide on incorporating an Editor into a Reactjs project

Currently, I am working with Reactjs and using the Nextjs framework. My goal is to integrate the "Tinymce" editor into my project and retrieve the editor value inside a formsubmit function. How can I achieve this? Below is my current code: const editor = ...

Launch the dev server in React

Begin by cloning the git code in React. Next, make sure to install npm package manager. Encountered Problem: I am facing an issue with running the dev-server. I have tried the following command in the cmd prompt: 1. npm run dev-server "Here is a sample ...

Creating a cookie within nextjs version 14

In developing my Next.js app, I encountered a challenge while setting up the authentication/authorization system. My approach involved using a refresh token with a long duration stored in an httpOnly cookie, along with an access token with a short duration ...

React Material UI and DayJs are not syncing up properly when displaying dates

In my React application, I am using MUI Cards to display a list of objects. One of the fields in these objects is of type date in postgres. When I retrieve a sample card object from the database, this is the value that appears in the browser console: { ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

Expanding a Landy react app to smoothly transition to a different page with the Router model

I am seeking assistance in updating the Landy out of the box application from https://github.com/Adrinlol/landy-react-template In a standard React/Javascript model, I would typically write code like the following: <Route path='/thanks' exact ...