Issue with ReactJS not applying classes based on conditions

I'm currently working on toggling a class on an element when a user clicks. However, I am facing an issue where my code only sets the class for a single element and does not refresh for subsequent clicks. Even though the set class is not being removed, my store seems to be updating correctly.

Below is my code:

class MyInterests extends Component {
    constructor(props) {
      super(props);
      this.state = {selected: []};
    }

    toggleChip(id, index, event){
        const { interestChanged } = this.props;
        let index = this.state.selected.indexOf(id);
        if(index === -1){
            this.state.selected.push(id);
        }else{
            this.state.selected.splice(index, 1);
        }
        interestChanged(this.state.selected);
    }

    render() {
    const {classes, myinterests: { categories, userinterest } } = this.props;
    const getClassNames = (id) => {
        return classNames(classes.chip, {[classes.selected]: (userinterest.indexOf(id) !== -1)});
    }
    return ( 
        /*..... Few elements to support styles....*/
          {categories.map((data, index) => {
               return (
                 <Chip
                    key={data._id.$oid}
                    label={data.name}
                    onClick={this.toggleChip.bind(this, data._id.$oid, index)}
                    className={getClassNames(data._id.$oid)}
                  />
              );
       })}
);
  }
}

Could someone please help me identify what's wrong in this code or suggest how I can achieve the desired functionality?

Answer №1

When dealing with immutable state, it's important to avoid using .push as it directly mutates the state. If you try to push a new element onto this.state.selected, you're essentially altering the state directly and not properly notifying React of the change, leaving your state vulnerable to future updates (remember that setState is asynchronous and batched for better performance). Check out this link for a solution. Instead, consider updating the state in a more efficient way:

// Make a copy of the current array
var selected = this.state.selected.slice();
// Add the new element to the copy
selected.push(id);
// Set the state with the modified copy
this.setState({ selected: selected });

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

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

Detecting planes using react-three/xr technology

I am utilizing react-three/xr and react-three/drei within my next.js project. This piece of code positions the 3D model in a fixed location. const TestComponent: NextPage = () => { return ( <div className="testar"> <ARCanv ...

Unable to initiate npm start due to author problem

I ran into an issue when trying to start npm in the command prompt: package.json: { "name": "reactapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "webpack-d ...

Encountering installation issues with Next.js and experiencing a package failure with react.js during the installation process

Issue: Error encountered during Next.js installation, multiple installation failures reported including missing packages peema@DESKTOP-6UGCO8V MINGW64 ~/Documents/alert/peeapp $ next build The module 'react' was not found. Next.js requires that ...

"Enhance User Experience with Multilevel Dropdowns in Bootstrap 4 - Submenus Aligned to the Top

I recently embarked on a project that involved using Bootstrap 4.4, The project is an eCommerce grocery store with departments comprising categories and subcategories. The main menu became very lengthy when using the default code, so I encountered some al ...

Update the logo for mobile, desktop, and tablet display using Bootstrap 4alpha

I am currently working on customizing a header with Bootstrap 4 alpha. <div class="container"> <div class="row"> <div class="col-md-6 text-md-left text-center"> <div class="navbar-brand"><img src="/wp-con ...

Having trouble with the position function in JavaScript?

I'm working on creating a small game, but I've encountered some difficulties at the start. Every time I attempt to obtain the position of track or trackCont, it consistently returns x: 0, y: 0. The DIV doesn't move to the correct position w ...

Retrieve the content of the second <li> element using jQuery

Seeking assistance with replacing the separator symbol in a given structure. In order to proceed, I first need to identify its position. Can anyone offer guidance on how to do this? Below is the structure in question: <div> <ul> ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Adjusting the dimension of a bootstrap button based on a value using React

Just getting started in the world of React and could use some assistance achieving this specific design: https://i.stack.imgur.com/E8PAr.png The buttons/widgets displayed above represent a certain number of items. I'm looking to adjust the size of t ...

What could be the reason for StaticComponent constantly re-rendering despite having a static state that does not change

I'm trying to grasp the core concepts of how React triggers component re-rendering upon state changes. In the scenario described below, the console.log('hi') statement within the StaticComponent is executed every time the onChange event han ...

The CSS file is not displaying the background image on the PHP file

I am facing an issue with using CSS to include a background image for the layer, but it doesn't seem to be working correctly... The CSS code snippet is as follows: header { background-image: url("boisko.jpg"); background-repeat: no-repeat; background ...

"Struggling with the height of Bootstrap row not filling the entire space

I've tried everything but nothing seems to be working. Whether it's a simple height: 100% or experimenting with flex-grow: 1, none of it is doing the trick. I'm having issues with this site I'm currently working on: https://i.sstatic.n ...

The axios.get method seems to be failing to return any data in the context of a

I am encountering an issue with a .get request as it is not returning any data. Any ideas on how to resolve this? GET http://localhost:8080/admin net::ERR_CONNECTION_REFUSED The Get Route is set up to filter items by username: app.get("/:username", ver ...

What methods are available for generating a short-lived banner using JavaScript?

I recently entered this industry and am in the process of constructing a website. Utilizing HTML and CSS, I crafted a cookie notification banner. I am seeking guidance on how to ensure that it only appears once "every 24 hours for each user." I attempted ...

React treats flat arrays and nested arrays in distinct ways

After some experimentation, I discovered an interesting behavior in React when passing nested arrays. Surprisingly, React renders the items properly without complaining about missing keys on the elements. const stuff = 'a,b,c'; // Nested Array ...

PostgreSQL dynamic query with Node.js

I am currently developing a note-taking app using REACT. My focus is on tracking only the changes made by the user to the note, rather than the current state of the note. For properties that have not been altered, I intend to send them as an empty string ...