Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created April 16, 2019 01:20
Show Gist options
  • Save sibelius/20659b4cd9be0ded32b53caa502e55fd to your computer and use it in GitHub Desktop.
Save sibelius/20659b4cd9be0ded32b53caa502e55fd to your computer and use it in GitHub Desktop.
UseEventEmitter hook to work with react navigation navigationOptions buttons
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]);
};
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