Skip to content

Instantly share code, notes, and snippets.

@wallergoble
Created March 22, 2023 18:28
Show Gist options
  • Save wallergoble/854bbe4d67c4adf331373c7ffda8353b to your computer and use it in GitHub Desktop.
Save wallergoble/854bbe4d67c4adf331373c7ffda8353b to your computer and use it in GitHub Desktop.
Recursive tokenizing react component
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