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

Achieving proper HTML element order?

Here is the HTML page I am working with: Click here to view the code on jsfiddle <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Extended UI</title> <style type="text/css"> .header{ padding-rig ...

Positioning two buttons side by side in separate columns on the same horizontal alignment

My objective is to arrange these two buttons horizontally on the same level with the help of bootstrap. <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href ...

What is the title of this particular CSS method?

I've been implementing a unique approach for more than a year now, and I have yet to come across similar practices elsewhere. Essentially, I am structuring display "states" or "modes" by utilizing CSS classes. Despite searching for terms like "css mod ...

Utilize the `addEventListener` and `removeEventListener` functions on the menu to

Why is my mobile menu not functioning correctly? The submenu should open on the first click and redirect to the parent URL on the second click, which works fine. However, when the window width increases to 768px or more, the submenu should appear on hover ...

Most effective method for designing a reusable <table> appearance

For my project, I need to create multiple tables using data from a database on different pages. I want to maintain a consistent styling throughout these tables: The first and last rows should have a bold font with reversed foreground/background colors. Th ...

Validating JSON form schemas in React

I am looking to implement field validation, specifically marking fields as required using the packageshttps://i.sstatic.net/upLt2.png "@rjsf/antd": v5 "@rjsf/core": v5 When I use the standard <Form /> component, everything works ...

Is there a way to keep this table fixed in place as the user scrolls?

Is there an alternative way to fix the content on the header so that it remains visible on the screen until the next table, even when scrolling? I've tried using position: sticky and top: 0, but the header still scrolls past. I have checked for any ov ...

How to Retrieve the Default Value in a React Hook?

I have a certain input field with a default value assigned to it. <input type="text" name="default" value="one" /> To handle the state of this input, I am utilizing a react hook. const [def, setdef] = useState({Defaul ...

When using jqueryprint.js to print from Firefox browser, an additional blank page appears before the content

Seeking assistance in printing a section of an HTML page using PHP with a large header space for empty space after printing. Despite multiple attempts, achieving the desired result in Chrome, but facing issues with Firefox, which adds an additional page be ...

The full extent of the background color is not reaching 100% of the height

My content wrapper has a height set to 100%, but the issue is that the background color doesn't fully extend across all content. Here are some images and my code for reference. Any assistance would be greatly appreciated! You can see the white space a ...

Concealing HTML content with a modal overlay

There are security concerns with my authentication overlay modal, especially for users familiar with CSS and HTML. Is there a way to hide the HTML behind the modal so it doesn't appear in the page source? The code below is just an example of a modal ...

Switch between different react components

When a component is opened, I want all other components to close. Whenever they are clicked, they will display a list. class ParentComponent extends Component{ constructor(props){ super(props) this.state= {...} } render(){ return( ...

What is the process for incorporating linear-gradient coloring into the background of a Material UI Chip component?

Is it possible to incorporate a linear-gradient below color as a background for Material UI Chip? linear-gradient(to right bottom, #430089, #82ffa1) The version of Material UI I am working with is v0.18.7. <Chip backgroundColor={indigo400} style={{widt ...

How can I adjust the positioning of labels in Semantic UI React?

Has anyone successfully changed the label position from right side to left? I attempted using float: left but it didn't have any effect. import {Radio } from "semantic-ui-react" <Radio label="in progress" toggle /> https://i.sstatic.net/hNGb6. ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

What is the best method to retrieve radio button labels from an array in React Native?

I came across an example of a radiobutton on the internet, which I found here: link. However, I have included only the parts that I used in the code. Now, I am looking to add labels from an array of strings. I'm not sure how to achieve this, so any ...

Beginner in html, css, and javascript: "Tips for saving jsfiddle demos?"

Recently, I developed an interest in JavaScript and CSS and came across some impressive examples on jsfiddle. I was wondering if there is a way to "export" these examples to my computer. Simply copying and pasting doesn't seem to work. How can I modi ...

The hyperlink to a different webpage does not trigger any JavaScript functionalities or render any CSS styles

I am facing an issue with linking HTML pages that run Javascript and JQuery Mobile from another HTML page. My link setup is as follows: <a href="hours.html">Hours</a> The linking page and the linked pages are in the same directory. However, ...

The React Material-UI Tab component threw an error message saying "Looking for an element type capable of holding a reference."

Currently, I am working on implementing React MUI Tabs into my project and encountering the following issue: Warning: Failed prop type: Invalid prop component supplied to ForwardRef(ButtonBase). Expected an element type that can hold a ref. Did you accid ...