I have this code:
import React, { useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
let str = "Hello ^world text '^Some^' '^Random^' '^Example^' '^Text^' '^Some^' '^more^' '^random^' '^example^' '^text^'!"
let arr = str.split(/\s/g)
let wordBits
const [highlightedWords, setHighlightedWords] = useState(["world", "example", "random"])
function highlighter(word) {
setHighlightedWords((prevState) => {
return(
[word, ...prevState]
)
})
}
return (
<View style={styles.container}>
<Text>
{arr.map((el) => {
wordBits = el.split("^")
token = wordBits[1]
return (
<Text>
{wordBits[0]}
<View style={
highlightedWords.includes(wordBits[1]) ?
styles.highlighted :
styles.regular
}>
<Text onPress={() => {highlighter(wordBits[1])}}>
{wordBits[1]}
</Text>
</View>
{wordBits[2]}{" "}
</Text>
)
})}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
highlighted: {
backgroundColor: "yellow"
},
regular: {
color: "black"
}
});
I extract the word from surrounding characters and try to pass it in as a function on each component. But instead, it gets set to the final word that got mapped.
Is there a way to pass the words themselves, and not change as the variable changes?