Skip to content

Instantly share code, notes, and snippets.

@alexpchin
Created Feb 28, 2019
Embed
What would you like to do?
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