How to prevent change, if no input or null input?
Having a Parent Component and a child, having input form in the child, and getting values from there. If am not inputting anything, it is taking the null
value. I want it to be default (or previous value or no change) if no input.
Parent
const Main = () => {
const todoData = [
{id:0,todoname:"Study",todotoday:"Completing CSS today"},
{id:1,todoname:"Coding",todotoday:"Leetcode 2 Problems"}
];
const [onEdit,setonEdit] = useState([]);
const [myArray,setmyArray] = useState(todoData);
const editData = (id,ehe,ela) =>{
console.log(id);
console.log("-->"+ehe);
setmyArray(myArray.map(obj =>{
if(obj.id === id){
return {...obj,todoname:ehe,todotoday : ela}
}else{
return obj;
}
}));
}
return(
{
myArray.map((obj)=>{
return (
<div className="todocont" key={obj.id}>
<div className="todobox" style={{opacity: checkedItems.includes(obj.id) ? 0.2 : '', }}>
<h2 className="head" >Todo: {obj.todoname}</h2>
<h3 className="todocont">{obj.todotoday}</h3>
<div className="todoboxbtn">
<TodoIcon />
</div>
</div>
<div className="editInput">
<SetEdit className="editComp" onSubmit={(input1,input2) => editData(obj.id,input1,input2)}/>
</div>
</div>
)
})
}
</div>
</div>
)
}
Child
import React, { useState } from 'react';
import './SetEdit.css';
const SetEdit = (props) => {
const [fh,setfh] = useState("");
const [El,setEl] = useState("");
const handleHead=(e)=>{
setfh(e.target.value);
console.log(fh);
}
const handleElab = (e) =>{
setEl(e.target.value);
}
const handleSubmit = (e) =>{
e.preventDefault();
props.onSubmit(fh,El);
}
return (
<div className='editInp'>
<form className='form' onSubmit={handleSubmit}>
<input type="text" placeholder='New Head' value={fh} onChange={handleHead}/>
<input type="text" placeholder='New Todo' value={El} onChange={handleElab}/>
<button className='btn'>Submit</button>
</form>
</div>
)
}
export default SetEdit
3
Answers
To keep the previous/default value if no input is provided in the child component, you can make use of controlled inputs and manage the state in the parent component.
In the child component (SetEdit), you can introduce additional state variables to store the previous/default values. Then, you can update these state variables only if the input values are provided.
You can keep the default value as previous like this,
This is pretty simple give an additional attribute to the input element
You need to give the name or id to the input field and than name typeOf