Home > Net >  How to remove or hide a div when checkbox is checked in React?
How to remove or hide a div when checkbox is checked in React?

Time:09-09

I am new to React and I am trying to build a simple todolist app.

Once a task is inserted, a div with an unchecked checkbox appears. Now, I'd like to hide or remove the div when the checkbox is clicked. I think I hooked up everything correctly but I miss, conceptually, what is the best way to do it: should I make a className attribute that changes upon clicking the checkbox? Should I modify the tasks array containing by removing the task that has been checked? Or, is there any other good way I could achieve this?

Thank you so much for your help.

https://scrimba.com/scrim/cof7e4dde89963549cc216a25 Here's the directly editable code

.insert {
    margin: 0 auto;
    display: block;
    padding: 20px;
    
    }
.enter--task {
    
    border-radius: 5px;
    
}

.tasks {
    width: 40%;
    min-height: 100%;
    color: black;
    background-color: white;
    margin-top: 20px;
    border-radius: 15px;
    line-height: 40px;
    padding: 10px; 
    overflow-wrap: break-word;
}

.task--check {
    
    margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React from "react"

export default function Insert () {
    
    const [task, setTask] = React.useState ("") // settin state for the single task, e.g. the input. 
    const [taskArray, setTaskArray] = React.useState ([]) // setting state for the array of tasks. 
    
    const tasks = taskArray.map((tasks) => {
        
         // {event.target.checked ? "hidden": "tasks"} this on className did not work.
        return (
        
            <div className="tasks"> 
                <input 
                    type="checkbox"
                    className="task--check"
                    onChange={handleCheck}
                />
                {tasks}
            
            </div>
            )
        
        
        })  // This is basically to return a series of paragraphs (soon divs) once enter or add task are clicked. 
    
    //How to let the task div disappear upon checking the checkbox?
    
    function handleCheck() {
        
        console.log(event.target.checked ? "checked": "unchecked")
        
    }
    
    function handleChange (event) {
        
        setTask(event.target.value)
    } // this is a function to register the value of the input. We use the setTask function to update the value of task to the value present in the input, which in this case it is our target
    
    function handleSubmit (event) {
        event.preventDefault()
        setTaskArray(task ? [...taskArray,task] : [...taskArray]) // quite hyped! Problem: user can input empty tasks. Solution: ternary operator saying, if task is true (truthy in this case, meaning a string with some content), add it to the taskArray. Otherwise, just return taskArray without appending the falsy task (empty string). 
        setTask("")
    }
    
    
    // this function handles the event after clicking enter or add task. First, we use event.preventDefault(): this is to avoid that every time that we click enter or add task, the page refreshes and the input is attached to the url (try to remove and see what happens). Then we have to make another array to insert the new task. To do this, we spread the previous array (taskArray) and we add the new element, which is task. After that, we reset the value of task to an empty string - this is to show the placeholder again. 
    
    return (
        
        <main className="insert">
            <form onSubmit={handleSubmit}>
                <input 
                    type="text" 
                    className="enter--task" 
                    placeholder="Enter your task"
                    onChange={handleChange} 
                    name="task"
                    value={task} // setting the value of my input equal to my state
                    
                     />
                <button>Add task</button>
            </form>
        
            {tasks}

        </main>
    )
}

CodePudding user response:

Create a state called checkState

const [checkState, setCheckState] = React.useState(false)

const handleCheck = (event) => {
   setCheckState(event.checked);
}

  <div className="tasks"> 
                <input 
                    type="checkbox"
                    checked={checkState}
                    onChange={handleCheck}
                />
                {tasks}
            
     </div>

{checkState && <div>Show div when checkbox checked</div>}

CodePudding user response:

I guess it depends on what you want to achieve, in the classic todo list example, we would remove the task from the state. By hiding it, you would keep the reference in memory. I'm not sure to see a good use case for it. If you want to remove, you could do it like this. Note that I'm using the index as key which is not recommended as the order of the items could change, instead you should add an id attribute to your tasks, and use it as the key. You will also use it to remove the task.

 const tasks = taskArray.map((task, i) => {
        
        return (
            <div className="tasks" key={i}> 
                <input 
                    type="checkbox"
                    className="task--check"
                    onChange={() => removeTask(i)}
                />
                {task}
            </div>
            )
        
        
        })  
    
    
    function removeTask(index) {
        setTaskArray(prev => prev.filter((_,i) => i !== index))
    }

  • Related