Created
April 16, 2019 01:20
-
-
Save sibelius/20659b4cd9be0ded32b53caa502e55fd to your computer and use it in GitHub Desktop.
UseEventEmitter hook to work with react navigation navigationOptions buttons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef } from 'react'; | |
export const useEventEmitter = (eventEmitter, eventName: string, fn: () => void) => { | |
const subscription = useRef(null); | |
useEffect(() => { | |
subscription.current = eventEmitter.addListener(eventName, fn); | |
return () => { | |
if (subscription.current) { | |
subscription.current.remove(); | |
} | |
} | |
}, [eventName]); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { EventEmitter } from 'fbemitter'; | |
const eventEmitter = new EventEmitter(); | |
const Emitters = { | |
cancel: 'cancel', | |
done: 'done', | |
}; | |
const MyComp = () => { | |
const handleCancel = () => {}; | |
const handleDone = () => {}; | |
useEventEmitter(eventEmitter, Emitters.cancel, handleCancel); | |
useEventEmitter(eventEmitter, Emitters.done, handleDone); | |
return (<Text>MyComp</Text>); | |
} | |
MyComp.navigationOptions = ({ screenProps: { t } }) => ({ | |
...CreateCommonSimpleHeader({ title: t('title') }), | |
headerLeft: ( | |
<NavBarIconButton | |
onPress={() => eventEmitter.emit(Emitters.cancel)} | |
> | |
times | |
</NavBarIconButton> | |
), | |
headerRight: ( | |
<TextMenuButton | |
onPress={() => eventEmitter.emit(Emitters.done)} | |
> | |
{t('Done')} | |
</TextMenuButton> | |
), | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment