I have this component called in the parent component:
{idEdit === comment._id && (
<InputComment
className={"comment-form-edit"}
onClick={sendEdit}
cancel={cancelEdit}
defaultValue={comment.comentario}
comentarioId={comment._id}
setFiles={setFiles}
files={files}
inputRef={inputRef}
// commentValue={commentValue}
// onChange={onChangeInputComment}
/>
)}
In this component, the user can type a comment or send files. However, when clicking on handleFile or handleRemoveFile, the value typed in the Comment input resets to the default value. As can be seen in the props passed by the parent component, I also tried setting a state on the Comment input value and onChange. It works, but every time I type a character, the input loses focus due to the re-rendering. Here’s the component:
const InputComment = ({
className,
onClick,
cancel,
defaultValue,
comentarioId,
setFiles,
files,
inputRef,
commentValue,
onChange
}) => {
const handleFile = useCallback(
(e, commentId) => {
const newFiles = Array.from(e.target.files);
setFiles((prevFiles) => ({
...prevFiles,
[commentId]: [...(prevFiles[commentId] || []), ...newFiles],
}));
},
[setFiles]
);
const handleRemoveFile = useCallback(
(index) => {
setFiles((prevFiles) => ({
...prevFiles,
[comentarioId]: prevFiles[comentarioId].filter((_, i) => i !== index),
}));
},
[comentarioId, setFiles]
);
return (
<>
<div>
<Comment
className={className}
ref={inputRef}
placeholder="Type a comment..."
// defaultValue={defaultValue}
// value={commentValue}
// onChange={(e)=>{onChange(e.target.value)}}
// value={comment}
// onChange={(e) => {
// handleChangeComment(e);
// }}
onChange={()=> {console.log(inputRef.current.value)}}
/>
<Button
component="label"
variant="outlined"
startIcon={<AttachFileIcon />}
style={{
marginTop: "-40px",
marginLeft: "8px",
}}
>
Send file
<VisuallyHiddenInput
type="file"
onChange={(e) => {
handleFile(e, comentarioId);
}}
multiple
/>
</Button>
</div>
<div style={{ display: "flex", gap: "1em" }}>
<Buttons variant="contained" onClick={() => onClick()}>
Send
</Buttons>
<Buttons variant="contained" onClick={() => cancel()} style={buttonCancel}>
Cancel
</Buttons>
{files && files[comentarioId] && files[comentarioId].length > 0 ? (
files[comentarioId].map((file, index) => {
return (
<div style={{ display: "flex" }} key={index}>
<p>{file.name}</p>
<IconButton
aria-label="remove"
style={{ color: "red" }}
onClick={() => {
handleRemoveFile(index);
}}
>
<HighlightOffIcon />
</IconButton>
</div>
);
})
) : null}
</div>
</>
);
};
export default InputComment;