개발/🟦 React
[문법] .map(), 컴포넌트, props 사용하여 각 동작 제어하기
비니_
2025. 1. 17. 20:34
728x90
2025.01.15 - [리액트] - [문법] 파라미터(props) 사용 (부모 -> 자식) 2
✔ 위의 글 코드 발전시키기
- 세개의 코드를 만들고 각각의 button으로 모달창 제어하기 + 모달창 안에 있는 글 수정 버튼을 누르면 해당 구이름 변경
코드 👇
import { useState } from 'react'
import './App.css'
function App() {
let [구이름, 구이름변경] = useState(['강남구', '송파구', '서초구']);
let [변경내용] = useState(['하남시', '여주', '파주']);
let [modal, setModal] = useState([false, false, false]);
return (
<>
<div>
{구이름.map((a, index) =>
<Div key={index} index={index} 구이름={구이름} setModal={setModal} modal={modal}/>
)}
{modal.map((isOpen, index) => isOpen ? (
<Modal
key={index}
className={'bg_yellow'}
index={index}
구이름={구이름}
구이름변경={구이름변경}
변경내용={변경내용}
/>
) : null)}
</div>
</>
)
}
function Div({ index, 구이름, setModal }){
return(
<>
<div style={{ marginTop: '10px' }}>
<span>{구이름[index]}</span>
<button onClick={() => {
setModal((prev) => {
const updatedModal = [...prev];
updatedModal[index] = !prev[index]; // 해당 인덱스의 모달 상태를 반전
return updatedModal;
});
}}>모달창</button>
</div>
</>
)
}
function Modal({ className, index, 구이름, 구이름변경, 변경내용 }){
const handleUpdate = () => {
구이름변경((prev) => {
const updatedNames = [...prev];
updatedNames[index] = 변경내용[index]; // 구이름[index]를 변경내용[index]로 업데이트
return updatedNames;
});
};
return(
<>
<div className={`modal ${className}`}>
<h2>{구이름[index]}</h2>
<p>날짜</p>
<p>상세내용</p>
<button onClick={handleUpdate}>글 수정</button>
</div>
</>
)
}
export default App;
결과 👇

1. span에 있는 강남구가 모달 h2에 똑같이 뜨고

2. 글수정을 누르면 변경내용의 값으로 바뀐다.
힘들어따....

728x90