Created
March 22, 2023 18:28
-
-
Save wallergoble/854bbe4d67c4adf331373c7ffda8353b to your computer and use it in GitHub Desktop.
Recursive tokenizing react component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
const Color = ({ color }) => <span style={{ color }}>{color}</span>; | |
const RecursiveText = ({ text }) => { | |
const words = text.split(' '); | |
const renderWord = (index) => { | |
if (index >= words.length) return null; | |
const word = words[index]; | |
if (['red', 'blue', 'green'].includes(word)) { | |
return ( | |
<React.Fragment> | |
<Color color={word} /> | |
{renderWord(index + 1)} | |
</React.Fragment> | |
); | |
} | |
return ( | |
<React.Fragment> | |
{word} | |
{renderWord(index + 1)} | |
</React.Fragment> | |
); | |
}; | |
return renderWord(0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment