Manipulate classes for buttons in a React component by adding or removing them

I'm attempting to create two buttons that will toggle their class when clicked. When button one is clicked, it should add the "active" class to itself and remove the "active" class from the sibling button.

I've made some progress, but I'm encountering an issue where I only want to add the active class when the element is clicked. Initially, the buttons should not have any classes. When the user clicks on the first button, the active class should be added to that button. Subsequently, if the user clicks on the second button, the active class should be removed from the first button and added to the second button. Another issue I'm facing is that when I click on an already selected and active button, the class and state change. It should be such that clicking on an already selected button does nothing, and the button with the active state should stay active. Essentially, it should function similarly to the jQuery toggleClass method.

Here's my updated react code:

import React, { Component } from "react";
import css from "./styles.css";

export default class TypeButtons extends Component {
  constructor(props) {
    super(props);
    this.state = { isActive: false };
  }

  toggleClass = () => {
    this.setState({ isActive: !this.state.isActive })
  }

  render() {
    return (
      <div className={css.buttonsContainer}>
        <button className={(this.state.isActive ? 'active' : '')} onClick={this.toggleClass}>
          Button 1
        </button>
        <button className={(this.state.isActive ? '' : 'active')} onClick={this.toggleClass}>
          Button 2
        </button>
      </div>
    );
  }
}

CSS:

.active {
  background: green;
}

I've created a CodeSandbox example: https://codesandbox.io/s/vigorous-pare-3zo0s

In summary, the class should only be added when the button is clicked, both buttons should not have the active class by default. Also, clicking on a button with the active class should not change it, the active state should only change when the opposite button is clicked.

Any assistance would be greatly appreciated!

Answer №1

https://codesandbox.io/s/silly-brown-qwerty

After reviewing your codesandbox, I made some edits. I used a state variable to keep track of the active button using a unique key. Initially, this key is set to null as per your request.

Instead of assigning integers to each button, you can customize them according to your preference. Additionally, you can utilize the .map() function to dynamically generate buttons, as exemplified in Constantin's response.

Answer №2

class ButtonGroup extends React.Component {
  constructor(props) {
    super(props);
    this.state = { selectedButton: "0" };
    this.buttonsList = [
        { id: "1", name: "Button 1" },
        { id: "2", name: "Button 2" }
    ];
  }

  handleClick = e => {        
    this.setState({ selectedButton: e.target.dataset.id });
  };

  render() {
    return (
        <div>
            {this.state.selectedButton}
            {this.buttonsList.map(({ id, name }) => {
                return (
                    <button
                        key={id}
                        data-id={id}
                        onClick={this.handleClick}
                        className={this.state.selectedButton === id ? "active" : ""}
                    >
                        {name}
                    </button>
                );
            })}
        </div>
    );
  }
}

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 is the process of mapping in a React Element?

I have encountered an issue while trying to implement my parameter, which is an array of objects. The error message I received states: Parameter 'option' implicitly has an 'any' type.ts(7006) I am unable to determine the cause of this ...

An issue occurred indicating "network detection failed" while trying to connect to Alchemy using the WebSocket provider

My task involves handling a file containing over 1 million ethereum addresses and private keys organized in a single file with only commas separating them. For instance: 0x7256bCf73C2309893AA12d6b26A142AB3097560c,0x5281130a3a84f531a1e30649a881207a65ce17f ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

I'm seeking assistance with a frontend script problem. I'm curious if there are alternative approaches to coding this script that may be more effective. Can anyone offer guidance on this?

As a frontend developer specializing in script injection, I have been utilizing Adobe Target to inject scripts. However, this method presents several challenges: 1. It is difficult to debug code errors as my HTML and CSS are wrapped inside ' ' a ...

The component is not receiving any props

In my house component, I retrieve a user's name and then verify its validity (using axios to check if the name is correct). If the name is valid and I click the button, I intend to display the Dashboard component. However, the issue arises when even a ...

I have implemented a custom-built sidebar component and I'm unsure about the process of adding data to it

After successfully incorporating this SideBar into my Vuex/Laravel project, I encountered a problem. The example code provided used: <div :class="$style.sidebar"/> However, when I tried to modify it to: <div :class="$style.sidebar">Content&l ...

Issue persists with Node Sass in current environment despite multiple attempts to resolve through rebuilds and uninstalls, specifically with version 4.12 on a 64

Currently, I am working with the most recent versions of Node (12.8) and Node-Sass package (4.12.0). You can find detailed documentation on these versions here: (https://github.com/sass/node-sass/releases). Despite my extensive research, whenever I try to ...

Center an image vertically and horizontally within a div element inside a container, even if the image sizes and aspect ratio differ, while also including padding

I am looking to vertically align images with varying ratios, where the image may be larger or smaller than the content and also include padding; I have tried different solutions found here, but none seem to cover all my requirements; I specifically need i ...

Enhance the performance of NodeJS by optimizing its operation within PM2 clusters

I have a production API running on a clustered nodejs setup using PM2, but I am concerned about its performance. Despite reading the PM2 documentation, I haven't found much information on performance optimization. Are there default limitations in eit ...

Differences between NextJS default server-side rendering and implementing a custom server

What are the benefits of using Express (or another server) when implementing SSR with Next.js instead of simply using the built-in next start command for initialization? ...

Tips for concealing validation errors in React Js when modifying the input field

I have recently started working with ReactJs, and I've implemented form validation using react-hook-form. After submitting the form, the errors are displayed correctly. However, the issue arises when I try to update the input fields as the error messa ...

Next.js App encounters a missing API route (The requested page is not found)

I have been working on a Next.js app and I created an api route for sending emails. Everything is functioning properly in my development environment. However, after deploying to production, I encountered a 404 error with the message "The page could not b ...

Error: Value not defined in the (Node, Express, Pug, JQuery) environment

I'm encountering a common issue as a beginner and could really use some assistance. I have tried multiple solutions but still can't resolve the error "ReferenceError: $ is not defined" when attempting to use jQuery. My project structure looks lik ...

Attempting to implement a Material UI dialog within a specialized contextual modal

I am experiencing an issue with my modal component that I have placed in a context. When I return html, including some divs, there are no issues. However, I would prefer to use the material-ui dialog for this purpose. Unfortunately, when I try to implemen ...

I am encountering an issue while attempting to load a model from file:// using @tensorflow/tfjs

I'm currently in the process of developing an npm package that is designed to load a pretrained tensorflow model and perform predictions based on it. Initially, everything worked fine when I used tf.loadLayersModel() with tf = require('@tensorfl ...

Contrary to expectations, the middleware EJS fails to render JPG files at

I am currently working on a NodeJS server using EJS. The goal of this server is to render an HTML page that contains a line of text and a jpg file. However, I am encountering an issue with the jpg file not being loaded by the server. Even though I have sp ...

Choosing Text with JavaScript

I am looking to enhance the appearance of text on an HTML page by making it bold. I have implemented the following code: <script type="text/javascript" > function getSelectedText(){ if(window.getSelection){ ; return window.getSelect ...

Complex React context information stored in sessionStorage

Within my React app, I am currently utilizing a context object to store user information. export const SessionContext = createContext(null); export const SessionContextProvider = ({ children }) => { console.debug("RTS Break SessionContextProvide ...

Enhance your video with Bootstrap 4 by overlaying text and buttons

I am in search of a solution that resembles the following design, but it needs to be styled using Bootstrap 4. Here is my current code snippet: <section class="banner embed-responsive-item"> <video class="hidden-sm-down" autoplay="" loop=""& ...

Is it possible to recognize when the mouse button is held down and the cursor is outside the viewport by using mouseleave detection?

Is there a way to detect when a user moves the mouse outside of the view-port, even if they are holding down the mouse button (for example, if the mouse is on the browser address bar)? In the code below, I am currently using mouseout and mouseleave to det ...