Giter Club home page Giter Club logo

react-inline-transition-group's Introduction

React Inline Transition Group

This component helps you to control transitions defined with inline styles. Built with ReactTransitionHooks, the goal is to supply a more up-to-date alternative to ReactCSSTransitionGroup.

Build Status Coverage Status

Advantages

  • You don't need to decouple your styles from the component.
  • You don't need to supply timeout properties as in ReactCSSTransitionGroup.
  • You have callbacks to control the start and end of your transitions for each child.
  • ReactCSSTransitionGroup uses timeouts to control the animations which means some situations can break its behavior, like in frame rates lower than 60fps.
  • ReactCSSTransitionGroup uses ReactTransitionGroup which means you can't interrupt animations.

Live Demo

Check out the demo.

How to install

npm install react-inline-transition-group

How to use

Import the component to your project and then wrap the nodes you want to control the transition with it. Example:

import React from 'react';
import ReactDOM from 'react-dom';
import Transition from 'react-inline-transition-group';

export default class Demo extends React.Component {
  constructor() {
    super();
    this.state = {count: 1};
  }

  handleAdd = () => {
    this.setState((previousState) => {
      return {count: previousState.count + 1};
    });
  };

  handleRemove = () => {
    this.setState((previousState) => {
      return {count: Math.max(previousState.count - 1, 0)};
    });
  };

  handlePhaseEnd = (phase, id) => {
    if (phase === 'leave') console.log(id + ' left');
  };

  render() {
    const styles = {
      container: {
        width: '500px',
      },

      base: {
        width: '100%',
        height: '50px',
        background: '#4CAF50',
        opacity: 0,
      },

      appear: {
        opacity: 1,
        transition: 'all 500ms',
      },

      leave: {
        opacity: 0,
        transition: 'all 250ms',
      },

      custom: {
        background: '#3F51B5',
      },
    };

    const elems = [];

    // Don't forget that for most React components use array indexes as
    // keys is a bad idea (but not for this example).
    for (let i = 0; i < this.state.count; i++)
      elems.push(<div key={i} id={i} style={i % 2 ? styles.custom : {}}>{i}</div>);

    return (
      <div>
        <div>
          <button onClick={this.handleAdd}>Add</button>
          <button onClick={this.handleRemove}>Remove</button>
        </div>
        <Transition
          childrenStyles={{
            base: styles.base,
            appear: styles.appear,
            enter: styles.appear,
            leave: styles.leave,
          }}
          onPhaseEnd={this.handlePhaseEnd}
          style={styles.container}
        >
          {elems}
        </Transition>
      </div>
    );
  }
}

ReactDOM.render(<Demo />, document.getElementById('container'));

Notice above that {elems} are divs, but they could be any other React component, just remember to pass the property style that your React component is receiving down to the HTML element that will get these styles. Example:

const SomeComponent = (props) => (
  <div style={props.style}>
    {props.children}
  </div>
);

const App = () => {
  const elems = [];

  // Don't worry, you can still apply custom styles to each element.
  const otherStyle = { ... };

  for (let i = 0; i < this.state.count; i++)
    elems.push(<SomeComponent style={otherStyle} key={i} id={i}>{i}</SomeComponent>);

  return (
    <Transition
      childrenStyles={{ ... }}
    >
      {elems}
    </Transition>
  );
};

Properties

Property name Description
component String. The component that will wrap all the children. Default: div.
childrenStyles Object. This object has the properties: base, appear, enter and leave. Each of these properties is another object containing the styles for the respective phase. The base styles are applied to all children in all phases.
onPhaseStart Function. Callback that will be called with the current phase (appear, enter or leave) and the child id when the phase begins, in this order.
onPhaseEnd Function. Callback that will be called with the current phase (appear, enter or leave) and the child id when the phase ends, in this order.

Notes

  1. You can pass an id property to your children components and the callback will be called with it so you know exactly for which child the event happened. This id is optional.

  2. The onPhaseStart callback will be called sooner a node is being added or removed to/from the group. If you have a delay in your CSS transition the component will not wait until the delay is complete to call the callback.

  3. The onPhaseEnd callback will be called when the longest transition time (delay + duration) completes. Notice that if a transition is interrupted this callback will not be called.

What is meant by phase

There are three phases in this component (the same as in ReactCSSTransitionGroup):

  • appear: happens to any child component that is already inside of ReactInlineTransitionGroup at the moment of its creation, or in other words, at the time the ReactInlineTransitionGroup component just mounted.

  • enter: happens to any child component that is inserted in ReactInlineTransitionGroup after its creation.

  • leave: happens to any child component that is being removed from ReactInlineTransitionGroup.

LICENSE

BSD-3

react-inline-transition-group's People

Contributors

axelg12 avatar casesandberg avatar felipethome avatar maxnowack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

react-inline-transition-group's Issues

React Style unit inference does not work anymore

When I wrap my components with a <Transition /> they loose the automatic units that react adds (e.g. in React doing style={{margin: 10}} would automatically convert it to style="margin: 10px", but the transition does not)

Example: if you inspect the children bellow, they have style="margin: 10" which is an invalid syntax. If you remove the <Transition> wrapper it works fine

class TransitionTest extends Component {

    state = {
        list: '1234567890'.split(''),
    };

    render () {
        const {list} = this.state;

        return (
        <div>
            <Transition
                childrenBaseStyle={{
                    margin: 10,
                }}
            >
                {list.map(num =>
                    <div
                        key={num}
                        onClick={() => this.setState({list: list.filter(id => id !== num)})}
                    >{num}</div>
                )}
            </Transition>
        </div>
        );
    }

}

Change styling for transitioning components

I am using react router to have view transitions. The issue I am having is that I want to change the childrenStyles prop to reflect the direction in which the user is navigating through the application. Currently the view that is leaving is not changing to the new styles that I supply it.

Can I please have an example of how to implement such a thing?

Children don't update their base styles

Awesome rewrite! It's getting there
One issue I'm having now in v2.0 is that if children update their styles, their props don't get updated.

Example:

class TransitionTest extends PureComponent {

    state = { size: 100 }

    render () {
        const {size} = this.state;
        console.log('--->', size)
        return (
        <Transition
            onClick={() => console.log('here') || this.setState({size: 50 + Math.random() * 100 | 0})}
            style={{position: 'absolute', top: 10, left: 10}}
        >
            <div style={{backgroundColor: 'red', width: size, height: size}} />
            <Test style={{backgroundColor: 'red', width: size, height: size}} />
        </Transition>
        );
    }

}

clicking the container does nothing even thought render() is called with the updated info. If you replace the Transition wrapper with a <div> it works as expected

Can't fade in Route(s) with react-inline-transition-group ( React-Router )

Iā€™m using react-inline-transition-group for, among other things, react-router transitions. Iā€™m using these settings & styles:

      <Transition
              childrenBaseStyle={this.styles['before']}
              childrenEnterStyle={this.styles['enter']}
              childrenAppearStyle={this.styles['appear']}
              childrenLeaveStyle={this.styles['leave']}
                                                                            >
             {React.cloneElement(this.props.children, {
                    key: this.props.location.pathname
              })}                                                                 
     </Transition>

      this.styles['before']      = {opacity: '0'}
      this.styles['enter']        = {opacity: '1', transition: 'opacity 400ms'}
      this.styles['appear']     = {opacity: '1', transition: 'opacity 400ms'}
      this.styles['leave']        = {opacity: '0', transition: 'opacity 400ms'}

When transitioning routes, the new route appears (without fade in) while the old route fades out properly.

My question is: How can I fade in the new route rather than it appearing suddenly. In other words, I want the new route to fade in while, simultaneously, the old route fades out.

Component element causing layout issues

The wrapping element is breaking some of my layouts. For example, if the parent of the transitioned element has display: flex, the transitioned element is no longer the direct child. Is it possible to have the ability to add inline styles to the component element?

Instance children do not receive style updates

The 2 <div>s bellow should essentially evaluate to the same thing, however the first one is missing the background property while the latter has it

class TransitionTest extends Component {

    render () {
        const TestClass = (props) => <div {...props}>test test</div>

        return (
            <Transition
                childrenBaseStyle={{
                    background: 'red',
                }}
            >
                <TestClass />
                <div>other test</div>
            </Transition>
        );
    }

}

Cannot change previous child's transition styles

I am wondering if it currently possible to change the styles for previous children.

I can create different styles for each group of children that are inside the <Transition> but I want to be able to apply styling to previous children. I think that the plugin does not consider any previous children that have not 'left' when applying styles.

How to use with react-router?

Hi, it would be great if there was an example of how to use this plugin correctly with react-router.

Currently, any transition that is added to the leaving route is not visible since react-router is not waiting for the transition to end before removing the route.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    šŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. šŸ“ŠšŸ“ˆšŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ā¤ļø Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.