I am trying to figure out a way to change the styling of multiple words each wrapped in a Text component in React Native, using an onPress event on each word.
I know how to do this in vanilla Javascript by running .split(" ") on a string to separate the words, and then mapping through them and wrapping them all in HTML elements like span tags with the word (in lowercase) as the class name and adding an onclick event that passes in the word .toLowerCase() as an argument to a function, which adds the word to an array of highlighted words, and then toggles adding or removing a class which will result in changing the styling of each instance of that word in a page.
The function would be something like this:
function exampleFunction(theWord) {
let temp = document.getElementsByClassName(theWord)
for (i = 0; i < temp.length; i++) {
if (temp[i].classList.contains("highlighted")) {
if (i === 0) {
let filteredArray = highlightedWords.filter((e) => e !== theWord)
highlightedWords = filteredArray
}
temp[i].classList.remove("highlighted")
} else {
if (i === 0) {
highlightedWords.push(theWord)
}
temp[i].classList.add("highlighted")
}
}
}
But the problem is that React Native doesn’t seem to use classes. And I am very new to React Native. So I am lost as to how to approach this issue.
Any help is greatly appreciated.
2
Answers
React uses a declarative instead of an imperative API as used in the DOM.
Therefore you should declare state which is the index of currently highlighted word (you can use a negative value to indicate that no word is highlighted). Then add the class
highlighted
only when theindex
of the word and the index in your state match. If one clicks on the same value again set thehighlighted
to a negative value again. React will automatically re-re-render whenever you update the state usingsetHighlighted()
.For react native , umm you cant do like that.
https://snack.expo.dev/ug8zEbrWZ
Please check working example above, and also do check out code here