Skip to content

Instantly share code, notes, and snippets.

@alexpchin
Created February 28, 2019 13:26
Show Gist options
  • Save alexpchin/072c9620ee79757178bd19b8cbb9f7ac to your computer and use it in GitHub Desktop.
Save alexpchin/072c9620ee79757178bd19b8cbb9f7ac to your computer and use it in GitHub Desktop.
Trying to get the tags to be highlighted
import React from "react";
import { StyleSheet, View, FlatList, Text } from "react-native";
import { connectInfiniteHits, connectHighlight } from "react-instantsearch-native";
import { uniqBy } from "lodash";
const Highlight = connectHighlight(
({ highlight, attribute, hit, highlightProperty }) => {
const parsedHit = highlight({
attribute,
hit,
highlightProperty: "_highlightResult"
});
const highlightedHit = parsedHit.map((part, idx) => {
if (part.isHighlighted)
return (
<Text key={idx} style={{ backgroundColor: "#ffff99" }}>
{part.value}
</Text>
);
return part.value;
});
return <Text>{highlightedHit}</Text>;
}
);
const HitsTags = connectInfiniteHits(({ hits, hasMore, refine }) => {
/* if there are still results, you can
call the refine function to load more */
const onEndReached = function() {
if (hasMore) {
refine();
}
};
const _renderItem = ({ item }) => {
return (
<View style={styles.container}>
<View style={styles.item}>
<Text>
#<Highlight attribute={"_tags"} hit={item} />
</Text>
</View>
</View>
);
};
const tags = uniqBy(
// Convert the Set to an array by spreading...
[
// new Set flattens the multidimensional array...
...new Set(
// Loop through the hit to get the highlighted array for _tags
hits.reduce(
(allTags, hits) => [
...allTags,
...((hits &&
hits._highlightResult &&
hits._highlightResult._tags) ||
[])
],
// Default argument for allTags reduce function
[]
)
)
],
"value"
)
// Pull the matches to the top
.sort(a => (a.matchLevel === "full" ? -1 : 1))
// Pull the fully matched items to the very top
.sort(a => (a.fullyHighlighted ? -1 : 1))
.map(hit => {
return {
_highlightResult: {
_tags: hit
}
};
});
return (
tags && (
<FlatList
style={{ backgroundColor: "red" }}
data={tags}
onEndReached={onEndReached}
keyExtractor={(item, index) => index.toString()}
renderItem={_renderItem}
/>
)
);
});
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center"
},
item: {
paddingHorizontal: 15,
paddingVertical: 15
}
});
export { HitsTags };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment