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

Time:10-19

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.

Thank you.

CodePudding user response:

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>

CodePudding user response:

I get you, first in the input to edit the todo you need to use the same value as what you used in adding todo. <input type="text" value={todos.text} onChange={EditHandler}/>

But in your todo app you use many state which make an app very hard to manage its state.

Lastly its bad practice to use useState function direct in the eventHandler function like what you have used in onDoubleClick.

Try to visit thinking in React by React js website. You will thanks your self for your time. https://reactjs.org/docs/thinking-in-react.html

  • Related