I currently working in a React Native project using 'https://www.npmjs.com/package/react-native-raw-bottom-sheet' lib to handle bottom up panel.
I want to trigger bottom up panel everytime I click a button in parent component instead of clicking a button in child component, how do I can achieve this.
Bottom Up Panel child component:
const refRBSheet : any = useRef();
View style={styles.container}>
<View style={{width:200}}>
<Button title="OPEN BOTTOM SHEET" onPress={() => refRBSheet.current.open()} />
</View>
<RBSheet
ref={refRBSheet}
closeOnDragDown={true}
closeOnPressMask={true}
animationType='slide'
customStyles={{
wrapper: {
backgroundColor: "transparent"
},
draggableIcon: {
backgroundColor: "#999999"
},
container:{
backgroundColor:'#101010',
height:450,
}
}}
>
<MyComponent/>
</RBSheet>
</View>
My parent component:
<View>
<Button title="I want to click this button and trigger ButtomUpPanel/>
<BottomUpPanel/>
</View>
CodePudding user response:
You need to use the useImperativeHandle
hook in your parent
const refRBSheet : any = useRef();
const open = () => {
refRBSheet.current.open()
};
useImperativeHandle(refRBSheet, () => ({
open,
}));
Then pass the ref
down to your components.
<View>
<Button onPress={()=>open()} title="I want to click this button and trigger ButtomUpPanel/>
<BottomUpPanel ref={refRBSheet} />
</View>
Remember useImperativeHandle
should be used with forwardRef
.
CodePudding user response:
Actually after hours of researching I finally found a way for my own question:
To pass a ref to child component from parent component I use
forwardRef
By importing import
{forwardRef} from 'react';
Then in my case i just wrap my child component in forwardRef:
const DetailPanelBottomUp: FC<IDetailPanel> = forwardRef(
({imgUrl, title, contentUrl,value}, ref: any) => {
return (
<View style={styles.container}>
<RBSheet
ref={ref}
onClose={() => setSocialNet(false)}
closeOnDragDown={true}
closeOnPressMask={true}
animationType="slide"
customStyles={{
wrapper: {
backgroundColor: 'transparent',
},
draggableIcon: {
backgroundColor: '#999999',
},
container: {
backgroundColor: '#101010',
height: 450,
},
}}>
<MyComponent/>
</RBSheet>
</View>
And in my parent component I just declare
useRef
and its action then pass the ref to child component as a props
const refRBSheet : any = useRef();
const open = () => {
refRBSheet.current.open();
};
<View>
<DetailPanelBottomUp title={actionItem.title} contentUrl={actionItem.src} ref=
{refRBSheet} imgUrl={actionItem.src} />
<Button onPress={()=>open()} title="I want to click this button and trigger ButtomUpPanel/>
</View>