[react] 자식컴포넌트->부모컴포넌트 데이터 전달

Yeong·2024년 9월 16일

자식컴포넌트에서 부모컴포넌트로 데이터 전달을 해야하는데 redux와 같은 상태관리없이 어떻게 하면 간단히 직관적으로 할 수 있을까 싶어 남겨보는 코드 !

🧚 자식컴포넌트

export default function Weather({getCity}) {
  function getWeatherMicro(lat, lon) {
    const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`;
    const microUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${API_KEY}`;
    Promise.all([
      fetch(weatherUrl).then(res=>res.json()),
      fetch(microUrl).then(res=>res.json()),
    ]). then(([weatherRes, microRes])=> {
      setWeatherData({city: weatherRes.name, weather: weatherRes.weather[0].main, temp: `${weatherRes.main.temp}°C`});
      
      getCity(weatherRes.name);
    })
    .catch((error) => {
      console.log('error:', error);
      setLoading(true);
    });
  }

getCity(weatherRes.name);를 통해 부모 컴포넌트로 받아온 city를 전달한다.

🧚 부모

const [city, setCity] = useState('');

  // 자식 컴포넌트에서 전달받은 city 값을 업데이트하는 함수
  const getCity = (cityName) => {
    setCity(cityName);
  };
    return (
        <Div>
          <Header city={city} />
          <Main>
            <Weather2 getCity={getCity} />
          </Main>  
		</Div>

0개의 댓글