Home > Enterprise >  How to create Expandable View for Product Details in React Native?
How to create Expandable View for Product Details in React Native?

Time:06-03

I'm having problem on creating an expandable view for the product details. Can anyone help me out on how to create an expandable view like the picture attached. I want like if a user clicks the product details container, it will show product details. Pls help me out as im quite new to react native.

Before pressed

Expandable View Image.

CodePudding user response:

First, create ExpandableView component that requires expanded prop. The prop itself should be set/updated in parent component (isExpanded). Add effect dependency to this expanded prop in ExpandableView to run the animation. Notice that every time isExpanded's value is changed, it rerenders ExpandableView component. Make sure rerendering happens only when needed, or you'll have performance issue.

import React, { useEffect, useState } from "react";
import {
  StyleSheet,
  View,
  TouchableOpacity,
  Animated,
  Text,
} from "react-native";

const ExpandableView = ({ expanded = false }) => {
  const [height] = useState(new Animated.Value(0));

  useEffect(() => {
    Animated.timing(height, {
      toValue: !expanded ? 200 : 0,
      duration: 150,
      useNativeDriver: false
    }).start();
  }, [expanded, height]);

  // console.log('rerendered');

  return (
    <Animated.View
      style={{ height, backgroundColor: "orange" }}
    ></Animated.View>
  );
};

function App() {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <View style={styles.app}>
      <TouchableOpacity
        onPress={() => {
          setIsExpanded(!isExpanded);
        }}
        style={styles.toggle}
      >
        <Text style={styles.toggleText}>Expand</Text>
      </TouchableOpacity>
      <ExpandableView expanded={isExpanded} />
    </View>
  );
}

const styles = StyleSheet.create({
  app: {},
  toggle: {
    width: 100,
    height: 30,
    backgroundColor: "blue",
    justifyContent: "center",
    alignItems: "center"
  },
  toggleText: {
    color: "#fff"
  }
});

export default App;

enter image description here

  • Related