osdnk / react-native-reanimated-bottom-sheet

Highly configurable bottom sheet component made with react-native-reanimated and react-native-gesture-handler
MIT License
3.33k stars 327 forks source link

How can I use this bottom sheet as a component? #248

Open dotpegaso opened 4 years ago

dotpegaso commented 4 years ago

Can I do something like this?

// components/BottomSheet.js
import React from 'react'
import ReanimatedBottomSheet from 'reanimated-bottom-sheet'
import { useWindowDimensions, View } from 'react-native'

const BottomSheet = ({ children }) => {
  const dimensions = useWindowDimensions()

  return (
    <View>
      <ReanimatedBottomSheet
        snapPoints={[0, dimensions.height - 200]}
        renderContent={children}
        initialSnap={0}
      />
    </View>
  )
}

export default BottomSheet

// pages/home.js
import BottomSheet from '../../components/BottomSheet'
...
return (
    <BottomSheet>
     ...
    </BottomSheet>
)
SConaway commented 4 years ago

No, because the renderChildren prop on ReanimatedBottomSheet expects a function which returns components. However, this would be easy to fix:

// components/BottomSheet.js
import React from 'react'
import ReanimatedBottomSheet from 'reanimated-bottom-sheet'
import { useWindowDimensions, View } from 'react-native'

const BottomSheet = ({ children }) => {
  const dimensions = useWindowDimensions()

  return (
    <View>
      <ReanimatedBottomSheet
        snapPoints={[0, dimensions.height - 200]}
        renderContent={() => children}
        initialSnap={0}
      />
    </View>
  )
}

export default BottomSheet

// pages/home.js
import BottomSheet from '../../components/BottomSheet'
...
return (
    <BottomSheet>
     ...
    </BottomSheet>
)
dotpegaso commented 4 years ago

@SConaway I see, thanks for the update!

But going this way, how can I handle the show/close action of the bottomsheet? We have ref in all examples so I'm bit confused about how to work with that since I couldn't find a properly way to use it as a props.

SConaway commented 4 years ago

Yeah, it takes a bit to get used to refs. basically, you would do something like this inside your functional component:

  const bottomSheet = useRef(null);
  // Then somewhere later, say in an onPress for a touchable
  // bottomSheet.current.snapTo(0); // Snaps to the first snapPoint
  // Or to close:
  // bottomSheet.current.snapTo(2); // Snaps to the last snapPoint, i.e., closed
 return (
        <View styles={styles.container}>
            // ...
            <BottomSheet
                snapPoints={400, 200, 0]}
                initialSnap={1}
                renderContent={renderDetails}
                renderHeader={renderHeader}
                ref={bottomSheet}
            />
        </View>

Check out this guide for some tips on refs in React. It's for regular React, but the concepts are the same.