So, are there any other ways, rather than changing value to defaultValue to change the input value manually? (When using defaultValue My program doesn't work properly)
ChildComponent = React.memo(
({ name, index, onChange, onDelete
}) => {
return (
<div>
<input value={name} onChange={onChange(index, name)} />
<button onClick = {() => onDelete(index)}>delete</button>
</div>
);
}
);
function App() {
const [names, setNames] = React.useState(["First", "Second"]);
const newName = React.useRef();
const onNameChange = (index: number, newName: string) => (event: {
target: { value: string };
}) => {
names[index] = event.target.value;
setNames(names);
};
function onNameDelete(index: number) {
const nameArr = [...names];
nameArr.splice(index, 1);
setNames(nameArr);
}
return (
<div>
{names.map((name, index) => (
<ChildComponent
key={index}
name={name}
index={index}
onChange={onNameChange}
onDelete={onNameDelete}
/>
))}
</div>
);
}
nameis initialized in state and how it is changed by onChange handler.