Modify styling of complete list upon clicking in React

For my latest project, I developed a basic todo application using React. One of the key features is that when a user clicks on a checkbox, the corresponding todo item's CSS changes to show a strike-through effect. Additionally, a button appears on hover which allows users to delete the specific todo item.

Currently, I am looking to implement two new functionalities:

  1. Modify the CSS of the entire list of todos upon clicking an 'x' event using React.
  2. Adjust the CSS of individual todos when clicking on the respective list item.

Below is a snippet of my app code:

class App extends Component {

  constructor(){
    super();
    this.state={
      todo:[]
    };
  };

  ...

I have added a method called "allDone()" and attached it to the span element 'X' via onClick event. However, I am encountering issues in changing the CSS of all elements in the list to display them as strikethrough. Check out the image here.

Answer №1

To update the class or add a new one in the 'allDone' function, you can utilize the forEach() statement and ensure to bind this function.

allDone = () => {
    var todos = this.state.todos;

    todos.forEach(function(item) {
      item.Decoration = "newTodo animated fadeInLeft strike";
    });

    this.setState({ todos: todos });
};

class App extends React.Component {

  constructor(){
    super();
    this.state={
      todos:[]
    };
  };

  enterTodo(keypress){
    var newTodo=this.refs.inputTodo.value;
    
    if( keypress.charCode == 13 )
    {
      this.setState({
        todos: this.state.todos.concat({Value:newTodo, Decoration:'newTodo animated fadeInLeft', checked:false})
      });

      this.refs.inputTodo.value=null;
    }
  }

  todo(text,i){
    return (
      <li className={text.Decoration}>
        <input type="checkbox" onChange={this.todoCompleted.bind(this,i)}className="option-input checkbox" checked={text.checked} />
        <div key={text.id}  className="item">
          {text.Value}
          <button type="button" className="destroy" onClick={this.remove.bind(this)}>X</button>
        </div>
      </li>
    );
  }

  remove(i){
    this.state.todos.splice(i,1);
    this.setState({todos:this.state.todos});
  }

  todoCompleted(i){
    var todo={...this.state.todos}
    
    if(todo[i].checked){
      this.state.todos[i].checked = false;
      this.state.todos[i].Decoration='newTodo';
      
      this.setState({
        todos: this.state.todos
      });
    } else {
      this.state.todos[i].checked = true;
      this.state.todos[i].Decoration= 'strike';

      this.setState({
        todos: this.state.todos
      });
    }
  }

  allDone = () => {
    var todos = this.state.todos;
    
    todos.forEach(function(item) {
      item.Decoration = "newTodo animated fadeInLeft strike";
    });

    this.setState({ todos: todos });
  }

  render() {
    return (
      <div>
        <h1 id='heading'>todos</h1>
        <div className="lines"></div>
        <div>
          <input type="text" ref= "inputTodo" onKeyPress={this.enterTodo.bind(this)} className="inputodo" placeholder='todos'/>
          <span onClick={this.allDone} id="all">x</span>
        </div>
        <div className="mainapp">
          <ul>
            {this.state.todos.map(this.todo.bind(this))}
          </ul>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<App/>,document.getElementById('app'));
.strike {
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>

Answer №2

Here's a solution that might help:

JavaScript

completeAllTasks() {
    let updatedTasks = this.state.tasks.map((task) => { return { Status: 'completed' } })
    this.setState({ tasks: updatedTasks }); 
}

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

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Shadow border added to each div creates a unique navigation tab for easy access

#container { position: fixed; height: 100%; left: 0px; right: 0px; top: 0px; width: 10%; background-color: blue; } #container>div {} <html> <div id="container"> <div>up</div> <div>down</div> <d ...

using mixins with styled-components

I have encountered a challenge while attempting to pass a mixin from Material UI to a styled-component. The problem lies in finding a way to transfer the mixin value to the styled-component without having to assign it to a css property. Unfortunately, dire ...

What methods can you use to locate the CSS selector within HTML that meets certain criteria?

Is it possible to parse a given link and find CSS selectors with attributes that partially or completely match a specific keyword? For example, if the keyword is "print," I want to identify all CSS selectors in the link containing "print" in their name, id ...

Checking and locating elements using Jquery's distinctive style

Within my code, I am searching for the DIV element that has the class .se and also has the attribute display: block. Once found, I need to retrieve the ID of this particular DIV. Unfortunately, it seems like my current approach is not correct. var usedse ...

What are the steps to execute a Next.js app post cloning the repository?

After creating a Next.js app using npx create-next-app@latest, I proceeded to push the new application to a GitHub repository. Upon cloning the repository into a fresh directory, I encountered an issue while attempting to execute the app with npm run dev. ...

I specialize in optimizing blog content by omitting the final line within a React framework

https://i.stack.imgur.com/WKOXT.png Currently, I have 4 lines and the 5th line in the current input field. This is my React code snippet: import { FC, useEffect, useState } from "react"; interface BlogWitterProps {} const BlogWitter: FC<B ...

Trapped in the clutches of the 'Access-Control-Allow-Origin' snag in our Node.js application

Our nodeJS application is deployed on AWS Lambda, and we are encountering an authentication issue with CORS policy when trying to make a request. The error in the console states: Access to XMLHttpRequest at 'https://vklut41ib9.execute-api.ap-south-1 ...

Is there a way to modify the color of an externally imported SVG within a React component?

Is it possible to modify the color of an SVG that is loaded from a server, rather than internally available? Here's an example where you can experiment by forking it. import styled from "styled-components"; const App = () => { return ...

Oops! There seems to be a server error with the PDFDownloadLink API. It appears that you are trying to use this web-specific API on Node, or perhaps your bundler is not loading react-pdf properly

I have developed a Report card generator in Next.js, and I am currently experimenting with the use of @react-pdf/renderer to generate PDFs before integrating it into my main project. However, I am encountering an error that I can't seem to resolve. S ...

Modify the appearance of the element that is currently chosen

I have a navigation menu and I would like to change the style of the element that is selected from the list in the navigation menu. I am using React with the Grid element from material-ui. NavigationMenu.tsx: import React, { useState, useEffect } from "r ...

Tips for Resizing google reCAPTCHA

The problem's image is shown below: Below is the code snippet related to the issue: <div class="text-xs-center" id="DIVCATCHA" runat="server"> <asp:HiddenField runat="server" ID="hdnImageSelected" /> <div class="g-recaptcha" data- ...

SetState function is not available, and the 'bind' operation has been successfully executed

I've encountered an issue with an input that has an onChange event. This input is part of a login form, which includes a password input and a submit button. The code seems simple enough and functions properly (I verified this through the console). Her ...

Adjust the padding of the React Table Material design

After implementing a Material React table component, I noticed that the header padding suddenly shifted to the left by 3rem. I've tried to override this style using Material UI styling without success. Here is a visual representation of the issue: ...

A <div> with relative positioning is inhibiting the visibility of absolutely positioned elements without any visible overlap

Recently, I encountered a strange issue on my webpage: Image of page The lines on the left side are supposed to be displayed behind or on top of the text box. However, when I increase their z-index, the lines extend all the way to the top of the page and g ...

Error: Definition Already Exists

I'm currently debugging a layout and encountering some peculiar errors. The page is being served as DTD XHTML 1.0 Strict. The error message looks like this: ID "OFFICENAME" already defined: div class="office" id="officename" ID "OFFICENAME" origin ...

Oops! You are required to utilize destructuring state assignment when working with React and WebSocket

Encountering an error stating "Must use destructuring state assignment" while working with React The code in question is located in "Home.jsx" The file containing the issue is named "MainPage.jsx". It involves sending user details to a server and receivi ...

Bizarre display of miscellaneous items on the monitor

Hey there, I've been working on creating a div to display information about both the Civilian and Vehicle that users input. Initially, everything worked perfectly with my HTML and CSS until I introduced two additional divs into the layout. With just o ...

Utilize Bootstrap's form-inline feature to arrange fields side by side in one neat

I am looking to customize my sign-in form layout by displaying the fields in a row next to each other rather than under each other. header: Update: I have successfully implemented this code <header class="navbar navbar-fixed-top navbar-inverse"> & ...

The no-unused-expressions rule is triggered when an assignment or function call is expected

I'm just starting out in full stack development and I'm experimenting with coding to improve my understanding of frontend using React JS and Material UI. While working on this component, I encountered an error in the console at line 75 (this.prop ...