Dracontis
Dracontis

Reputation: 4364

How could you pause animation in react-transition-group while loading initial data in components?

I have following App component:

            <Route render={( { location } ) => (
                <TransitionGroup component="div" className="content">
                    <CSSTransition key={location.key} classNames="slide" timeout={{
                        enter: 1000,
                        exit: 300
                    }} appear>
                        <Switch location={location}>
                            <Route exact path='/' component={Intro}/>
                            <Route path="/history" component={History}/>
                            <Route path="/rules" component={Rules}/>
                            <Route path="/faq" component={Faq}/>
                            <Route path="/feedback" component={Feedback}/>
                            <Route path="/partners" component={Partners}/>
                        </Switch>
                    </CSSTransition>
                </TransitionGroup>
            )}/>

And it works fine, but every animation executes immediately. For example, if I go from /rules to /history, I got full animation on both components, but history component require data from the server, so animation applied on empty container.

How could I pause animation in react-transition-group components? I have Redux, so I could change loading variable anywhere in my app. Also, I don't want to preload all data in the store on app start.

Upvotes: 8

Views: 2607

Answers (3)

Tiago Coelho
Tiago Coelho

Reputation: 5101

I would make your component return null when it's loading and make the loading state determine the CSSTransition key like <CSSTransition key={location.key+loading?'-loading':''}

see example here: https://stackblitz.com/edit/react-anim-route-once

note that to make this work without duplication I had to make the component copy the loading prop and persist it in state, so that one of the copies of the component never displays (which would create a duplication of the component as seen here: https://stackblitz.com/edit/react-anim-route-twice)

    <Route render={({ location }) => (
      <TransitionGroup component="div" className="content">
        <CSSTransition key={location.key+(this.state.loading?'-loading':'-loaded')} classNames="crossFade" timeout={{
          enter: 3000,
          exit: 3000
        }} appear>
          <Switch location={location} >
            <Route exact path='/' component={Hello} />
            <Route exact path='/history' render={() =>
              <Delayed setLoading={this.handleSetLoading} loading={this.state.loading} />} />

          </Switch>

        </CSSTransition>
      </TransitionGroup>
    )} />

and in the component something like this:

export default class History extends React.Component {
  state={loading:this.props.loading}
  componentDidMount() {
    setTimeout(() => {
      this.props.setLoading(false);
    }, 2000);
  }
  render() {
    return !this.state.loading ? <div><h1>History! <Link to="/">Home</Link></h1></div> : null;
  }
}

Upvotes: 2

Dracontis
Dracontis

Reputation: 4364

I've done peloading through redux and redux-saga. Maybe it's one and only way to achieve following with react-router and react-transition-group, because transition toggle animation anytime when render method is run, even if it return null.

I've implemented following actions:

const LoadingActions = {
    START_LOADING: 'START_LOADING',
    STOP_LOADING: 'STOP_LOADING',
    REDIRECT: 'REDIRECT',

    startLoading: () => ({
        type: LoadingActions.START_LOADING
    }),

    stopLoading: () => ({
        type: LoadingActions.STOP_LOADING
    }),

    redirect: ( url, token ) => ({
        type: LoadingActions.REDIRECT,
        payload: {
            url,
            token
        }
    })
};

export default LoadingActions;

In the reducers I've implemented simple loader reducer, that will toggle on and off loading variable:

import { LoadingActions } from "../actions";

const INITIAL_STATE = {
    loading: false
};

export default function ( state = INITIAL_STATE, { type } ) {
    switch ( type ) {
        case LoadingActions.START_LOADING:
            return { loading: true };
        case LoadingActions.STOP_LOADING:
            return { loading: false };
        default:
            return state;
    }
}

The most irritating thing is reducer chain - this.props.loader.loading. Too complex for such simple thing.

import { combineReducers } from "redux";
...
import LoadingReducer from './LoadingReducer';

export default combineReducers( {
    ...
    loader: LoadingReducer
} );

This most work goes in saga:

function* redirect ( action ) {
    yield put( LoadingActions.startLoading() );
    const { url } = action.payload;

    switch ( url ) {
        case MENU_URL.EXCHANGE:
            yield call( getExchangeData, action );
            break;
        ... other urls...
    }
    yield put( LoadingActions.stopLoading() );
    BrowserHistory.push( url );
}

... loaders ...


function* watchRedirect () {
    yield takeLatest( LoadingActions.REDIRECT, redirect );
}

const sagas = all( [
    ...
    fork( watchRedirect )
] );

export default sagas;

I put listener on redirect action, so it will call redirect generator. It will start loading and call data preloading yield call will await for preload to finish and after it will stop loading and redirect. Though it won't wait for positive result, so preloaders should handle errors themselves.

I hoped that I could avoid redux complexity with built-in feature of router or transition library, but it has no such tools to stop transition. So it is one of the best way to achieve transition with preloded data.

Upvotes: 0

Olivier Butler
Olivier Butler

Reputation: 183

So my cases have been a bit different but they might help you think of a solution.

  1. You can delay the initial display easily by adding an if (this.state.isloaded == true) block around your whole router. Start loading when your component mounts, and when the async call completes, setState({isloaded: true}).
  2. You can make your own <Link> component, which launches a request, and only once it’s complete changes the page location. You can do whatever special loading spinners you like in the meantime.

Basically, keep the routing and transition components to one side. I find them to be brittle and painful with cases like this. Let me know if you want any more details or snippets.

Upvotes: 1

Related Questions