Search code examples
javascriptcssreactjsecmascript-6use-effect

Select and deselect multiple div in react-js


In react-js click a div that div will highlight and click again it will normal, we select multiple div and unselect, select maximum four div only these are the conditions. I beginner in react-js my div are ,

<div className='todoDiv select'>Task1</div>
<div className='todoDiv'>Task2</div>
<div className='todoDiv'>Task3</div>
<div className='todoDiv'>Task4</div>
<div className='todoDiv'>Task5</div>

here select class is used to highlight the div, how to solve this problem i have basic knowledge in react-js please help me


Solution

  • I'd approach this by storing an array of todo objects in state with useState(), and maintain a selected property for each todo. As the todos are clicked, the selected property is changed.

    To limit the selections to 4, simply add a check with a count like below.

    CodeSandbox demo

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    
    function App() {
      const [todos, setTodos] = useState([
        { id: "1", name: "Task 1", selected: true },
        { id: "2", name: "Task 2", selected: false },
        { id: "3", name: "Task 3", selected: false },
        { id: "4", name: "Task 4", selected: false },
        { id: "5", name: "Task 5", selected: false }
      ]);
    
      const todoClicked = (e) => {
        // max 4 selected
        if (!e.target.classList.contains("selected")) {
          const selectedCount = todos.filter((todo) => todo.selected).length;
          if (selectedCount === 4) {
            return;
          }
        }
    
        setTodos(
          todos.map((todo) =>
            todo.id === e.target.getAttribute("data-id")
              ? { ...todo, selected: !todo.selected }
              : todo
          )
        );
      };
    
      return (
        <div>
          {todos.map((todo) => (
            <div
              onClick={todoClicked}
              data-id={todo.id}
              key={todo.id}
              className={`todoDiv${todo.selected ? " selected" : ""}`}
            >
              {todo.name}
            </div>
          ))}
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById("container"));