onAddPokemon이 함수가 아니라는 오류가 발생. 이건 onAddPokemon 함수가 PokemonList 컴포넌트로 올바르게 전달되지 않았거나, 함수가 누락되었을 때 발생 가능.
이 문제를 해결하기 위해 PokemonContext를 이용하여 addPokemon 함수를 전달하는 방식으로 수정하기.
```pokemonContext.jsx```
import React, { createContext, useContext, useState } from 'react';
const PokemonContext = createContext();
export function PokemonProvider({ children }) {
const [selectedPokemon, setSelectedPokemon] = useState([]);
const addPokemon = (pokemon) => {
if (selectedPokemon.length >= 6) {
alert("최대 6개의 포켓몬만 선택할 수 있습니다.");
return;
}
if (selectedPokemon.find((p) => p.id === pokemon.id)) {
alert("이미 선택된 포켓몬입니다.");
return;
}
setSelectedPokemon((prev) => [...prev, pokemon]);
};
const removePokemon = (pokemonId) => {
setSelectedPokemon((prev) => prev.filter((pokemon) => pokemon.id !== pokemonId));
};
return (
<PokemonContext.Provider value={{ selectedPokemon, addPokemon, removePokemon }}>
{children}
</PokemonContext.Provider>
);
}
export function usePokemon() {
return useContext(PokemonContext);
}
```pokemonlist.jsx```
import React from "react";
import styled from "styled-components";
import PokemonCard from "./PokemonCard";
import MOCK_DATA from "../Data/MOCK_DATA";
import { usePokemon } from "../context/PokemonContext"; // usePokemon import
const PokemonListContainer = styled.div`
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
margin-top: 20px;
`;
function PokemonList() {
const { addPokemon } = usePokemon(); // usePokemon으로 addPokemon 가져오기
return (
<PokemonListContainer>
{MOCK_DATA.map((pokemon) => (
<PokemonCard
key={pokemon.id}
pokemon={pokemon}
onAdd={() => addPokemon(pokemon)} // addPokemon 전달
/>
))}
</PokemonListContainer>
);
}
export default PokemonList;
```pokemoncard.jsx```
import React from "react";
import styled from "styled-components";
const CardContainer = styled.div`
width: 150px;
border: 1px solid #ddd;
border-radius: 10px;
padding: 15px;
text-align: center;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.2s;
cursor: pointer;
&:hover {
transform: scale(1.05);
}
`;
const PokemonImage = styled.img`
width: 80px;
height: 80px;
`;
const PokemonName = styled.h3`
font-size: 1rem;
margin: 10px 0 5px;
`;
const AddButton = styled.button`
padding: 8px 16px;
background-color: #ff6347;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 0.9rem;
transition: background-color 0.2s;
&:hover {
background-color: #ff4500;
}
`;
function PokemonCard({ pokemon, onAdd }) {
return (
<CardContainer>
<PokemonImage src={pokemon.img_url} alt={pokemon.korean_name} />
<PokemonName>{pokemon.korean_name}</PokemonName>
<AddButton onClick={onAdd}>추가</AddButton> {/* onAdd 함수 호출 */}
</CardContainer>
);
}
export default PokemonCard;
오늘은 배포까지햇고 내일은 조금더 수정예정 ㅠㅠ
'REACT' 카테고리의 다른 글
뉴스피드 팀프 (5) | 2024.11.15 |
---|---|
24.11.13 (0) | 2024.11.13 |
REACT 포켓몬 도감 만들기 DAY_1 (0) | 2024.11.06 |
REACT Supabase (0) | 2024.11.05 |
React Router (0) | 2024.11.05 |