I have a custom input component that has an edit mode, I use multiple inputs and my goal is to extract all the state from the input and put it on the parent.
I managed to do it for the input value since I create a useState for every input, but how can I achieve the same thing for the toggle behavior. I want to have a button next to each input that toggles the state of the input.(Show/Hide the input).
Right now when I press edit all the edits Booleans get triggered so all the inputs become visible.
How can I toggle one input at a time from the parent, Basically I want my custom components to be purely for presentation and the state should live on the parent
Example:
const Parent = () => {
const [value1, setValue1] = useState('')
const [value2, setValue2] = useState('')
const [value3, setValue3] = useState('')
const [editMode, setEditMode] = useState(false)
return (
<div>
<ChildCustomInput value={value1} updateValue={setValue1} editMode={editMode} updateEditMode={setEditMode} />
<ChildCustomInput value={value2} updateValue={setValue2} editMode={editMode} updateEditMode={setEditMode}/>
<ChildCustomInput value={value3} updateValue={setValue3} editMode={editMode} updateEditMode={setEditMode}/>
</div>
)
}
const ChildCustomInput = (props)=> {
// ref to update the input's value in the parent
const textInputEl = useRef(null)
// method to update the parent's values
const updateComponentValue = () => {
props.updateValue(textInputEl.current.value)
props.updateEditMode(!props.editMode)
}
// Toggle Edit mode
const changeEditMode = () => {
props.updateEditMode(!props.editMode)
}
const renderEditView = () => {
return (
<div>
<input ref={textInputEl}></input>
<button onClick={updateComponentValue}>
OK
</button>
</div>
)
}
const renderDefaultView = () => {
return (
<div>
<div>
{props.value}
</div>
<button onClick={changeEditMode}>
EDIT
</button>
</div>
)
}
return (
<div>
{
props.editMode
? renderEditView()
: renderDefaultView()
}
</div>
)
}
export default Parent;