What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array.

Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected.

                        <div className='synonym-keeper'>
                            {synArr.map((syn) => (
                                <button
                                    className={`synonym ${isPressed && 'active'}`}
                                    onClick={() => toggleIsPressed(!isPressed)}
                                >
                                    {syn}
                                </button>
                            ))}
                        </div>

How can I modify my code so that only the CSS class of the selected button toggles?

Answer №1

Introduce a new component named Togglebutton to store the toggle functionality within it. This approach allows you to toggle each button individually.

An alternative solution could be:

const synArr = ["button 1", "button 2", "button 3"];

const ToggleButton = ({ text }) => {
  const [isPressed, toggleIsPressed] = React.useState(false);

  return (
    <button
      className={`synonym ${isPressed && "active"}`}
      onClick={() => toggleIsPressed(!isPressed)}
    >
      {text}
    </button>
  );
};

function App() {
  return (
    <div className="synonym-keeper">
      {synArr.map((syn) => (
        <ToggleButton text={syn} key={syn}/>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
.synonym.active {
  background-color: green;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Answer №2

I came up with a solution by creating an array for the className and updating its content onClick, like this:

                        <div className='synonym-keeper'>
                            {synArr.map((syn, idx) => (
                                <button
                                    className={`synonym ${isPressed[idx]}`}
                                    onClick={() => {
                                        const newIsPressed = [...isPressed];
                                        newIsPressed[idx] === ''
                                            ? (newIsPressed[idx] = 'active')
                                            : (newIsPressed[idx] = '');
                                        setIsPressed(newIsPressed);
                                    }}
                                >
                                    {syn}
                                </button>
                            ))}
                        </div>

This solution resolves the issue and allows me to choose one or more buttons in sequence. Amila's answer impressed me with its simplicity, so I will mark theirs as accepted.

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

Angular directive becomes disabled when transferred between different DOM elements

In my app, I utilize a modal service that handles the opening and closing of modals. The modal retrieves its content from a specific div with an ID located within a hidden container element. This process typically functions correctly. The issue I am encou ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

Mapping a list with sections can easily be achieved by breaking down the elements

I'm facing an issue with listing array data under sections using .map in React. I know how to use .map to list the entire array, but struggling to list each item under its respective section. Currently, I have to use .map separately for each section. ...

Container containing sliding content underneath

I've designed a grid with separate boxes that reveal related content when clicked. The display of this content is achieved using jQuery's slideToggle feature. The setup functions smoothly, with each row containing clickable boxes that unveil the ...

Issue with Ajax call not triggering the Controller Action in MVC

I am encountering an issue with making an ajax call to the controller action method that returns a json object. In addition, I need to pass the integer CheckID to the method. Any assistance would be greatly appreciated. Thank you in advance! ***View*** ...

Within the useEffect hook, the React state is found to be void

I am currently working on developing a chat app using Pusher and React. My goal is to maintain a list of online users. The code snippet I am using is as follows: const [users, setUsers] = useState([]); useEffect(() => { // UseEffect so only called at fi ...

What is the definition of the term "WebapiError"?

I'm currently developing a Spotify Web App that focuses on retrieving the top albums of KD Rusha using the Client ID and Artist ID to exclusively fetch his releases on Spotify. To accomplish this, I am utilizing an npm package called spotify-web-api-n ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

Retrieve nested JSON data from an AJAX request

Currently, I am working with an API that provides JSON data back to me. The challenge I'm facing is figuring out how to access this data and showcase it on my HTML webpage since the results are stored in server memory rather than a file. Below is an e ...

Enhance Laravel 5 by integrating browserify into the Elixir build process

My workflow for transforming coffee to js using browserify, browserify-shim, and coffeeify looks like this: I work with two main files: app.coffee and _app.coffee, designated for frontend and backend respectively. These files are located in resources/coff ...

Launched a website, but I can't access it because of the HSTS restriction

After deploying my website, I encountered an issue where I couldn't access it due to HSTS. I reached out to Namecheap, the domain registrar, for assistance but they mentioned that the problem lies with the hosting provider. I am currently using surge ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

What is the best way to access elements of a certain class that begin with a specific string?

Here's the scenario: I have a group of elements that each have multiple classes assigned to them. Take a look at this example: <input class="etape btn-info others"> <input class="etape btn-inverse others"> <input class="etape btn-dange ...

How can I access the value of `var` from inside the return statement of a React component?

I am facing an issue where I need to retrieve the value of googleToken from within a <div> element in the return statement of my React Component. Despite the fact that the value has been updated, it keeps showing the initial state as null const Layou ...

Unable to render content following API request

Looking for assistance with a coding dilemma I've been stuck on for weeks. Here's the snippet of code causing me trouble: getNews() { var news_items = new Array(); AsyncStorage.setItem('time', JSON.stringify({'last_cache&a ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...

Tips for maintaining synchronization of Next.js data between re-renders?

My Next.js application retrieves a user's profile data on a server-rendered 'page' component. This data is then passed to various client-side components for viewing and editing purposes. Whenever a user makes changes, fetch requests are sent ...

The CSS property 'clear:both;' is not functioning properly on IE7 browsers whereas works fine on IE8/IE9, Firefox, Chrome, and other browsers

I have been receiving feedback from visitors about some issues on one of my websites. Those who reached out to us are using IE7 on Windows XP. I was able to recreate the problem by using IE7 or by mimicking it in compatibility mode with IE7 document mode o ...