Make animated collapsible card component, with initial props to show or hide

Viewed 11306

Background

Using React Native I was able to make collapsible card component. On Icon click the card slides up hiding its content, or expands showing its content. I would think setting the default value would be as easy as setting expanded to false or true, but I think the problem here is that when it is toggled an animation is triggered which changes the height of the card.

Example

class CardCollapsible extends Component{
  constructor(props){
    super(props);

    this.state = {
      title: props.title,
      expanded: true,
      animation: new Animated.Value(),
      iconExpand: "keyboard-arrow-down",
    };
  }

  _setMaxHeight(event){
      this.setState({
          maxHeight   : event.nativeEvent.layout.height
      });
  }

  _setMinHeight(event){
      this.setState({
          minHeight   : event.nativeEvent.layout.height
      });

      this.toggle = this.toggle.bind(this);
  }

  toggle(){
    let initialValue    = this.state.expanded? this.state.maxHeight + this.state.minHeight : this.state.minHeight,
        finalValue      = this.state.expanded? this.state.minHeight : this.state.maxHeight + this.state.minHeight;

    this.setState({
      expanded : !this.state.expanded
    });

    if (this.state.iconExpand === "keyboard-arrow-up") {
      this.setState({
        iconExpand : "keyboard-arrow-down"
      })
    } else {
      this.setState({
        iconExpand : "keyboard-arrow-up"
      })
    }
    this.state.animation.setValue(initialValue);
    Animated.spring( this.state.animation, {
        toValue: finalValue
      }
    ).start();
  }

  render(){

    return (
      <Animated.View style={[styles.container,{height: this.state.animation}]}>
          <View style={styles.titleContainer} onLayout={this._setMinHeight.bind(this)}>
            <CardTitle>{this.state.title}</CardTitle>
            <TouchableHighlight
              style={styles.button}
              onPress={this.toggle}
              underlayColor="#f1f1f1">
              <Icon
                name={this.state.iconExpand}
                style={{ fontSize: 30 }}/>
            </TouchableHighlight>
          </View>
          <Separator />
          <View style={styles.card} onLayout={this._setMaxHeight.bind(this)}>
            {this.props.children}
          </View>
      </Animated.View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    margin:10,
    overflow:'hidden'
    },
  titleContainer: {
    flexDirection: 'row'
    },
  card: {
    padding: 10
  }
});

export { CardCollapsible };

Open

enter image description here

Closed

enter image description here

Question

My goal is to allow a person calling the component to set the initial state of the component to expanded or open. But when I try changing the expanded state to false it does not render closed.

How would I go about allowing the user calling the component to select whether it is expanded or closed on initial component render?

5 Answers
// With hooks for rn


import React, { useState, useEffect } from 'react'
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    StyleSheet
  } from 'react-native'
  import styles from '../../assets/styles' 
  const usePanelExpanding = (props) => {


    let icons = {
        'up': require('../../images/formicons/icons/close.png'),
        'down': require('../../images/formicons/icons/disclosure.png')
      }

      const [expanded, setExpanded] = useState(false);
      const [iconShow, setIconShow] = useState('up');
      const [textSwap, setTextSwap] = useState('Show more...');


      useEffect(
        () => {
          expanded ? setIconShow('up') : setIconShow('down')
          expanded ? setTextSwap('Show less') : setTextSwap('Show more ...')
        },
        [expanded]
      );

      const toggle = () =>{
        setExpanded(!expanded)
      }

      const panel = (<View>
        <View style={styles.titleContainer} >
            <TouchableOpacity
                style={styles.button}
                onPress={toggle} >
                <Image
                    style={styles.buttonImage}
                    source={icons[iconShow]} />
            </TouchableOpacity>
        </View>
        {expanded && <View style={styles.mainPageFull} >
            {props}
        </View>
      }
      </View>)
      return {
        panel,
        toggle
      }
  }
  export default usePanelExpanding


// How to use it from a parent function

 const expandingBioObject = usePanelExpanding(<Text>{profile.bio}</Text>)
<Card title="Biography" containerStyle={styles.CardContainerBio}>
      {expandingBioObject.panel}
      </Card>

use react-native-collapsible-view. you can pass it expanded property which allows you to fully control the collapsible state by other components.
you can also leave him self-controlled but pass initExpanded which allows you to choose what is the initial state of the collapsible.

Related