input으로 입력을 받아 list에 추가하여 렌더링을 하는 코드를 작성해보자.
import React,{useRef, useState} from 'react';
import './index.css';
import CreateChampion from './CreateChampion';
function Champion({champion}){
return(
<div>
<b>{champion.name}</b> <br/>
<span>스킬: {champion.skill}</span>
<div><br/></div>
</div>
)
}
function ChampionList({champions}) {
return (
<div>
{champions.map(champion =>(
<Champion champion={champion} key={champion.id}/>
))}
</div>
);
}
function App(){
const listId = useRef(4);
const [champions, setChampions] = useState(
[
{
id: 1,
name: '갱플랭크',
skill: '혀어어어업상'
},
{
id: 2,
name: '갈리오',
skill: '단호한 일격'
},
{
id: 3,
name: '가렌',
skill: '결정타'
}
]
)
return(
<div>
<CreateChampion listId={listId} champions={champions} setChampions={setChampions}/>
<ChampionList champions={champions}/>
</div>
)
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import App from './App'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
import React,{useState} from 'react';
function CreateChampion({listId, champions, setChampions}){
const [inputs, setInputs] = useState({
name : '',
skill : ''
});
const {name, skill} = inputs;
const onChange = e => {
const {name, value} = e.target;
setInputs({
...inputs,
[name] : value
})
}
const onInsert = () => {
const Champion = {
id: listId.current,
name: name,
skill: skill
}
console.log(Champion)
setChampions(champions.concat(Champion));
setInputs({
name: '',
skill: ''
})
listId.current+=1;
}
return(
<div>
<input name="name" onChange={onChange} placeholder="챔피언 이름" value={name}/>
<input name="skill" onChange={onChange} placeholder="스킬" value={skill}/>
<button onClick={onInsert}>등록</button>
</div>
)
}
export default CreateChampion;
- userRef를 사용하여 배열의 id가 초기화되지 않도록 하였다.
- 구조적으로 잘 짜여진 코드는 아니지만 그래도 잘 돌아가게 작성하여 보았다.