React CSStransition или React-spring в map ()

Может ли кто-нибудь объяснить, как сделать плавный переход, такой как непрозрачность 0 - непрозрачность 1 с помощью CSStransiton или анимации реакции-пружины, когда данные поступают с сервера, и я делаю карту div мгновенно появляется без перехода.

Я хочу сделать переход при отправке формы, когда я возвращаю данные из map (), может ли кто-нибудь показать мне, как добавить этот переход с помощью CSStransition или react-spring.

import React, {useState} from "react";
import axios from "axios";
import moment from "moment";

import { KEY } from "../../const";
import { cloudy, hurricane, rain, snow, sunny } from "./weatherType";

import "./winderCondition.scss";
import "./weather.scss";
import {CSSTransition} from "react-transition-group";

export const Weather = () => {
  const [currentWeatherData, setCurrentWeatherData] = useState([]);
  const [foreCast, setForeCast] = useState([]);
  const [query, setQuery] = useState("");

  const getCurrentWeather = async (query: string) => {
    const response = await axios.get(`https://api.weatherbit.io/v2.0/current?&city=${query ? query : ""}&key=${KEY}`)
    setCurrentWeatherData(response.data.data)
  };

  const getForecast = async (query: string) => {
    const response = await axios.get(`https://api.weatherbit.io/v2.0/forecast/daily?&city=${query ? query : ""}&key=${KEY}&days=5`)
    setForeCast(response.data.data);
    foreCast.shift();
  };

  const handleCityChange = (e: any) => {
    setQuery(e.target.value);
  };

  const handleOnSubmit = async (e: any) => {
    e.preventDefault();
  await getCurrentWeather(query);
  await getForecast(query);
  };

  const getCondition = (weatherCode: number) => {
    if (weatherCode >= 200 && weatherCode <= 233) {
      return hurricane;
    }

    if (weatherCode >= 300 && weatherCode <= 522) {
      return rain;
    }

    if (weatherCode >= 600 && weatherCode <= 610) {
      return snow;
    }

    if (weatherCode === 800) {
      return sunny;
    }

    if (weatherCode >= 801 && weatherCode <= 900) {
      return cloudy;
    }
  };

  return (
    <div className="weather">
      <form onSubmit={handleOnSubmit}>
        <div className="input_wrapper">
        <input className="city-input"
          type="text"
          onChange={(e) => handleCityChange(e)}
          value={query}
          name="city"
        />
        <label className={query.length !== 0 ? "move-up" : "city-label"} htmlFor="city">Your City</label>
        </div>
          <button type="submit">Search</button>
      </form>
        <div className="weather-wrapper">
          {currentWeatherData &&
          currentWeatherData.map((weather: any) => {
            return (
                <CSSTransition classNames="my-node" key={weather.city_name} in={true} timeout={300}>
                <div className="currentWeather">
                  <div className="gradient">
                    <div className="country">
                      Location: {`${weather.city_name}, ${weather.country_code}`}
                    </div>
                    <div className="temperature">
                      {Math.floor(weather.temp)} °C
                    </div>
                    {getCondition(weather.weather.code)}
                    <div>{weather.weather.description}</div>
                  </div>
                </div>
            </CSSTransition>
            );
          })}
          <div className="forecast-wrapper">
            {foreCast &&
            foreCast.map((weather: any) => {
              return (
                  <div className="forecast" key={weather.ts}>
                    <div className="forecast-date">
                      {moment(weather.ts * 1000).format("dddd")}
                    </div>
                    <div>{Math.round(weather.temp)} °C</div>
                    <img
                        className="forecast-icon"
                        src={`https://www.weatherbit.io/static/img/icons/${weather.weather.icon}.png`}
                        alt="weather-condition"
                    />
                  </div>
              );
            })}
          </div>
        </div>
    </div>
  );
};

CSS

  .my-node-enter {
    opacity: 0;
  }
  .my-node-enter-active {
    opacity: 1;
    transition: opacity 500ms;
  }
  .my-node-exit {
    opacity: 1;
  }
  .my-node-exit-active {
    opacity: 0;
    transition: opacity 500ms;
  }

person Aw KingOftheworld    schedule 07.03.2021    source источник


Ответы (1)


просто нужно было добавить еще одну опору со значением true appear={true} и classNames для нее.

<CSSTransition classNames="fade" key={weather.city_name} in={true} timeout={500} appear={true]>
                <div className="currentWeather">
                  <div className="gradient">
                    <div className="country">
                      Location: {`${weather.city_name}, ${weather.country_code}`}
                    </div>
                    <div className="temperature">
                      {Math.floor(weather.temp)} °C
                    </div>
                    {getCondition(weather.weather.code)}
                    <div>{weather.weather.description}</div>
                  </div>
                </div>
            </CSSTransition>

  .fade-appear {
    opacity: 0.01;
  }

  .fade-appear.fade-appear-active {
    opacity: 1;
    transition: opacity 500ms ease-in;
  }
thanks to user "wherewereat" from reddit

person Aw KingOftheworld    schedule 08.03.2021