How can I fix the issue of the onClick function in my React list not activating the toggle?

How to Activate Toggle Functionality

Currently, I am working on a project using React where I developed a list with active states. I have implemented the onClick functions, but unfortunately, they are not working as intended. When I click on the list items, all I see is a quick flash of the background color that should indicate the active state of the div.

import React, { useState } from 'react';
import './Home.css';

function Home() {
  const [isActive, setIsActive] = useState({
    oneStar: true,
    twoStars: false,
    threeStars: false,
    fourStars: false,
    fiveStars: false,
  });

  return (
    <div className='app_card_container'>
      <div className='app_card_body'>
        <div className='app_card_list'>
          <div
            className={isActive.oneStar
              ? 'app_card_lists active'
              : 'app_card_lists'
            }
            onClick={() =>
              setIsActive({
                oneStar: true,
                twoStars: false,
                threeStars: false,
                fourStars: false,
                fiveStars: false,
              })
            }
          >
            1
          </div>
          <div
            className={isActive.twoStars
              ? 'app_card_lists active'
              : 'app_card_lists'
            }
            onClick={() =>
              setIsActive({
                oneStar: false,
                twoStars: true,
                threeStars: false,
                fourStars: false,
                fiveStars: false,
              })
            }
          >
            2
          </div>
          <div
            className={isActive.threeStars
              ? 'app_card_lists active'
              : 'app_card_lists'
            }
            onClick={() =>
              setIsActive({
                oneStar: false,
                twoStars: false,
                threeStars: true,
                fourStars: false,
                fiveStars: false,
              })
            }
          >
            3
          </div>
          <div
            className={isActive.fourStars
              ? 'app_card_lists active'
              : 'app_card_lists'
            }
            onClick={() =>
              setIsActive({
                oneStar: false,
                twoStars: false,
                threeStars: false,
                fourStars: true,
                fiveStars: false,
              })
            }
          >
            4
          </div>
          <div
            className={isActive.fiveStars
              ? 'app_card_lists active'
              : 'app_card_lists'
            }
            onClick={() =>
              setIsActive({
                oneStar: false,
                twoStars: false,
                threeStars: false,
                fourStars: false,
                fiveStars: true,
              })
            }
          >
            5
          </div>
        </div>
      </div>
    </div>
  );
}

export default Home;

For the CSS regarding the involved component, here is what I have implemented:

.app_card_list {
  display: flex;
  flex-direction: row;
}

.app_card_lists {
  margin-left: 1.5rem;
  display: flex;
  flex-direction: row;
  justify-content: center;
  width: 35px;
  height: 35px;
  background-color: hsl(216, 12%, 8%);
  text-align: center;
  align-items: center;
  border-radius: 50%;
  cursor: pointer;
  color: hsl(0, 0%, 100%);
}

.app_card_lists:hover {
  background-color: hsl(217, 12%, 63%);
}

.app_card_lists:active {
  background-color: red;
}

Answer №1

An ":active" state/attribute is different from an "active" CSS class.

className={isActive.oneStar ? 'app_card_lists active' : 'app_card_lists'}

When an element is marked as "active", it should have both the "app_card_lists" and the "active" classes. The CSS styling should look something like this:

.app_card_lists {
  margin-left: 1.5rem;
  display: flex;
  flex-direction: row;
  justify-content: center;
  width: 35px;
  height: 35px;
  background-color: hsl(216, 12%, 8%);
  text-align: center;
  align-items: center;
  border-radius: 50%;
  cursor: pointer;
  color: hsl(0, 0%, 100%);
}

.active { /* defines the active state CSS class */
  background-color: red;
}

If you want the "active" styling to apply only to specific elements, you can use a more targeted selector.

.app_card_lists.active { /* targets elements with both app_card_lists and active classes */
  background-color: red;
}

Answer №2

Upon reviewing your code

app_card_lists active

it appears that you are expecting a class named active in your CSS file:

.active {
  background-color:  red;
}

Based on your code, you are checking for the absence of the :active state in a div element, which does not actually have this state.

For more information, please refer to mdn resources

Answer №3

Follow these steps to update your state:

const [selectedStars, setSelectedStars] = useState(1)

Now, implement your clickable star component like this:

<div 
    className={selectedStars <= 1 ? 'star active' : 'star'} 
    onClick={() => setSelectedStars(1)}
>
1
</div>
<div 
    className={selectedStars <= 2 ? 'star active' : 'star'} 
    onClick={() => setSelectedStars(2)}
>
2
</div>
<div 
    className={selectedStars <= 3 ? 'star active' : 'star'} 
    onClick={() => setSelectedStars(3)}
>
3
</div>
<div 
    className={selectedStars <= 4 ? 'star active' : 'star'} 
    onClick={() => setSelectedStars(4)}
>
4
</div>
<div 
    className={selectedStars <= 5 ? 'star active' : 'star'} 
    onClick={() => setSelectedStars(5)}
>
5
</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

Utilizing a local video file as a video background in HTML and CSS

I've hit a roadblock while attempting to set a video on my computer as the background. The video file is named "runbg.avi" and it resides in the same folder as my HTML and CSS files. After scouring through numerous websites, I encountered a couple of ...

Execute the JavaScript callback

I am encountering an issue when trying to pass an anonymous function as a callback and call it. I seem to be missing something simple, because I keep getting the error 'Uncaught type error - callback is not a function'. Here is what I am attempti ...

Angular animation not firing on exit

I am encountering an issue with my tooltip component's animations. The ":enter" animation is working as expected, but the ":leave" animation never seems to trigger. For reference, here is a link to stackblitz: https://stackblitz.com/edit/building-too ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

Utilizing a jQuery variable within an .html() method

Can a Jquery if statement be used to display different content inside a div based on a variable? For example, if the variable is set to "cats", the displayed content might say "I like cats", and if it changes to "dogs", it would read "I like dogs". Is this ...

Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo). <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE ...

Develop a dynamic daily messaging system

I'm interested in incorporating a daily changing message feature on my website. My plan is to store all the messages in a MySQL database and have them displayed daily. Any guidance on how to achieve this would be highly appreciated! Thank you, I ha ...

Can Reactstrap integrate seamlessly with Bootstrap version 5?

I encountered an error while using reactstrap, bootstrap, and nextjs Server Error SyntaxError: The requested module 'react-popper' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by impor ...

Effortless rendering of React components using a CDN and Heroku for a seamless

Struggling to configure a server-side rendered React app that is deployed through CircleCI on Heroku for the node/express backend, with CloudFront acting as the CDN. I am facing difficulties in visualizing how all of this will seamlessly come together. Th ...

Why is fading out columns in an HTML table with jQuery's .fadeTo() method taking so long?

I am looking to implement a functionality where all cells in a column of my HTML table fade out when I click on a button located in the header of that column. I have written the following JavaScript code to achieve this: ... myDOMElement.find(".headerIcon ...

React does not always remove event listeners when using the useEffect hook's return callback

I have a functionality in my component where it initializes a key event listener. This event is supposed to trigger an API call to fetch random data. useEffect(() => { const keyUpEvent = (event) => { if (event.code === "Enter") { ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

The Gatsby Head API is experiencing issues with correctly formatting scripts

I'm currently exploring the use of Gatsby's Head API with Gatsby.js (4.24.2) and TypeScript, and I am encountering some inconsistent outcomes. Here is the code I am working with, it is functional but certain scripts are failing to compile: const ...

How can we capture and execute a function on the server in Next.js in response to a user's request for the index page (/)?

Is it possible to use a middleware function or another method in Next.js to check if a user is trying to access the home page? My goal is to intervene when a user tries to reach the home page. Intercepting a URL request is quite straightforward with Next. ...

What is the best way to ensure that my button only reveals the corresponding div in its group upon clicking?

Currently, when I click the first button, both hidden divs are showing. I want it so that when I click the first button, only the hidden div in its group is shown. Similarly, when I click the second button, only the hidden div in its group is shown. Can s ...

When encountering a TypeError where it is not possible to read the property 'data' of an undefined value, the result returned may be

How can I retrieve a value when selecting an element from an array that doesn't have an index? For instance: var series = [{data: [10]}, {data: []}, {data: []}, {data: []}, {data: [10]}, {data: []}, {data: [10]}, {data: []}, {data: []}, {d ...

The jQuery .load() function does not seem to be functioning properly on secure HTTPS connections

After implementing an SSL certificate through Cloudflare on my website, I encountered an issue where a specific function returned an error code 0 and failed to load the URL content. How can I resolve this issue? $(function () { EnderReact(); }); functi ...

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

What setting should I adjust in order to modify the color in question?

Looking to Customize Radar Chart Highlighted Line Colors https://i.sstatic.net/PqWc4.png I am currently working on a Radar Chart and I am trying to figure out which property needs to be edited in order to change the color of the highlighted lines. I have ...

Is there a way to specifically target the reCAPTCHA element in an iframe in order to display it without any other elements using Gatsby/React?

Currently, I am facing a challenge with my website contact form. I am using an iframe from Shopify for submission and it's set to "display: none" so I can use my own styled contact form. However, the issue is that the iframe contains a reCAPTCHA verif ...