Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// -----------------
// This system replaces this existing Flare event system and its concept of Event Components.
// -----------------
// Here's an example of how we might make a Pressable View:
// PressableView.js
import {usePressResponder} from "react-events/press";
import {useFocusResponder} from "react-events/focus";
import {useHoverResponder} from "react-events/hover";
export default function PressableView(props) {
const pressEvents = {
onPress: props.onPress,
...
};
const focusEvents = {
onFocus: props.onFocus,
...
};
const hoverEvents = {
...
};
const targetRef = useRef(null);
const [pressed] = usePressResponder(targetRef, pressEvents)
const [focused] = useFocusResponder(targetRef, focusEvents)
const [hovered] = useHoverResponder(targetRef, hoverEvents)
const childState = {
focused,
pressed,
hovered
};
const children = props.children;
if (typeof children === 'function') {
return <div ref={targetRef}>{children(childState)}</div>;
}
return <div ref={targetRef}>{props.children}</div>
}
// -----------------
// Here is how we can consume our PressableView.
// -----------------
// App.js
import PressableView from 'PressableView';
export default function App() {
function handlePress() {
console.log('You pressed me!');
}
return (
<PressableView onPress={handlePress}>
{({pressed}) => (
<Text>{pressed ? 'Nice press!' : 'Press me!'}</Text>
)}
</PressableView>
);
}
// -----------------
// When events are fired from Flare responders, such as `press` or `focuswithin`,
// we can listen for these events (defined in the responder).
// -----------------
// Using `useListener` or `createListener`, this can be done in the tree:
const PressListener = React.createListener(PressResponder);
export default function App() {
function handlePressOuter() {
console.log('You pressed outer!');
}
function handlePressInner() {
console.log('You pressed inner!');
}
return (
<PressListener onPress={handlePressOuter}>
<PressableView onPress={handlePressInner}>
...
</PressableView>
</PressListener>
);
}
// -----------------
// The important thing to note is that the listener components will only
// capture events that have been defined as bubbling:
// -----------------
// Inside Press.js
context.dispatchEvent(eventObject, listener, eventPriority, bubbles);
// So this can allow certain non-bubbling events to not traverse up the tree.
// For example `focus`, `blur` and `scroll`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.