When I selected a ID in select box, I want to put a new name in the selected ID of the names array. I used useState and useRef, but "splice" dosen't work. I don't know how to pass the selected ID to splice function. It's so hard to me. Help me, please.
import React, { useRef, useState } from 'react';
const App = ()=>{
const [names, setNames] = useState([
{id: 1, text: 'aaa'},
{id: 2, text: '222'},
{id: 3, text: 'bbb'},
]);
const [inputText, setInputText] = useState('');
const [nextId, setNextId] = useState(4);
const onChange = e => setInputText(e.target.value);
const inputEl = useRef(null);
const optionId = useRef(null);
const onClick = () => {
const nextNames = names.concat({
id: nextId,
text: inputText,
});
setNextId(nextId + 1);
setNames(nextNames);
setInputText('');
console.log(inputEl.current);
console.log(optionId.current);
};
const onSelect = id => {
const nextNames = names.splice(id, 0, {id:id, text: inputText});
setNames(nextNames);
setInputText('');
}
const onRemove = id => {
const nextNames = names.filter(name => name.id !== id);
setNames(nextNames);
};
const nameList = names.map(name => (
<li key={name.id} onDoubleClick={()=> onRemove(name.id)}>{name.text}</li>
));
const idOption = names.map((name, index)=>(
<option key={name.id}>{index}</option>
));
return(
<div>
<input value={inputText} onChange={onChange} ref={inputEl}/>
<button onClick={onClick}>추가</button>
<select ref={optionId} onSelect={onSelect}>
<option>ID</option>
{idOption}
<option>last</option>
</select>
<ul>{nameList}</ul>
</div>
);
};