Browse Source

Document how to avoid wrapper in ReactTransitionGroup

Thanks to @rayshan for some rewording tips too!
main
Dan Abramov 9 years ago
parent
commit
cbfdf2ff4f
  1. 29
      docs/10.1-animation.md

29
docs/10.1-animation.md

@ -238,8 +238,6 @@ By default `ReactTransitionGroup` renders as a `span`. You can change this behav
</ReactTransitionGroup>
```
Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! Just write `component={List}` and your component will receive `this.props.children`.
Any additional, user-defined, properties will become properties of the rendered component. For example, here's how you would render a `<ul>` with CSS class:
```javascript{1}
@ -247,3 +245,30 @@ Any additional, user-defined, properties will become properties of the rendered
...
</ReactTransitionGroup>
```
Every DOM component that React can render is available for use. However, `component` does not need to be a DOM component. It can be any React component you want; even ones you've written yourself! Just write `component={List}` and your component will receive `this.props.children`.
### Rendering a Single Child
People often use `ReactTransitionGroup` to animate mounting and unmounting of a single child such as a collapsible panel. Normally `ReactTransitionGroup` wraps all its children in a `span` (or a custom `component` as described above). This is because any React component has to return a single root element, and `ReactTransitionGroup` is no exception to this rule.
However if you only need to render a single child inside `ReactTransitionGroup`, you can completely avoid wrapping it in a `<span>` or any other DOM component. To do this, create a custom component that renders the first child passed to it directly:
```javascript{1}
var FirstChild = React.createClass({
render: function() {
var children = React.Children.toArray(this.props.children);
return children[0] || null;
}
});
```
Now you can specify `FirstChild` as the `component` prop in `<ReactTransitionGroup>` props and avoid any wrappers in the result DOM:
```javascript{1}
<ReactTransitionGroup component={FirstChild}>
{someCondition ? <MyComponent /> : null}
</ReactTransitionGroup>
```
This only works when you are animating a single child in and out, such as a collapsible panel. This approach wouldn't work when animating multiple children or replacing the single child with another child, such as an image carousel. For an image carousel, while the current image is animating out, another image will animate in, so `<ReactTransitionGroup>` needs to give them a common DOM parent. You can't avoid the wrapper for multiple children, but you can customize the wrapper with the `component` prop as described above.

Loading…
Cancel
Save