Search code examples
javascriptreactjstodomvc

React todolist onDoubleclick Input edit value show the current value instead of empty


I'm trying to create a todolist with React which when you double click on one of the to do list that will show input that allow you to edit the value. But I want to show the before value in the input edit when user click on it and the user can erase the before value and change to new and change the value.

I know, my explanation is very bad. I will show the example that I want in here https://todomvc.com/examples/react/#/. I want to make just like this person todo mvc which when you double click the todolist the edit input value still shown the before value.

import {useState} from 'react';

export default function App() {
  const [todo, setTodo] = useState([])
  const [input, setInput] = useState('')
  const [edit, setEditing]= useState(null)
  const [edittext , setEditingText] = useState('')

  const InputHandler = (e)=>{
    setInput(e.target.value)
  }

  const SubmitHandler = ()=>{
    setTodo([...todo, {text:input, id: Math.random()*1000}])
    setInput('')
  }
  const EditHandler = (e)=>{
    setEditingText(e.target.value)
    console.log(e.target.value)
  }

  const SubmitEdit = (id)=>{
    setTodo([...todo].map((todos)=>{
      if(todos.id === id){
        todos.text = edittext
      }
      return todos
    }))
    setEditing(null)
    setEditingText("")
  }
  return (
    <div className="App">
    <input value={input} onChange={InputHandler}/>
    <button onClick={SubmitHandler}>Add</button>  
    {todo.map(todos =>
      <div key={todos.id}>
        {edit === todos.id ? 
       (<><input type="text" value={edittext} onChange={EditHandler}/>
       <button onClick={()=>SubmitEdit(todos.id)}>Edit</button></>)
        : (<p onDoubleClick={()=>setEditing(todos.id)}>{todos.text}</p>)
        }
      </div>
    )}  
    </div>
  );
}

I'm sorry if my explanation is a little confusing.


Solution

  • It's all good, just update the editing text as well on double click.

    <p onDoubleClick={()=>{setEditing(todos.id); setEditingText(todos.text)}}>{todos.text}</p>