score:2

Accepted answer

sure thing, it's not really hard at all once you know the right tools.

here's a codesandbox example i whipped up, and a snippet of the same below (slightly adjusted for stack overflow's ancient babel version).

the idea is:

  • use string.split's regexp mode to split the string into fragments that are either brackets or aren't
  • iterate over those fragments to keep track of the nesting level for the brackets (to properly colorize pairs)
  • finally, return a react fragment with those children (this way we don't have to deal with array keys)

the colors in this example are only 3 levels deep, but you could easily add more, or make the colorization loop over n colors using the modulus operator.

function brackethighlighter({ text }) {
  const children = react.usememo(() => {
    const out = [];
    let level = 0;
    text.split(/([()])/).foreach((bit) => {
      if (bit === "(") {
        level++;
        out.push(<span classname={"l" + level}>{bit}</span>);
      } else if (bit === ")") {
        out.push(<span classname={"l" + level}>{bit}</span>);
        level--;
      } else {
        out.push(bit);
      }
    });
    return out;
  }, [text]);
  return react.createelement(react.fragment, {}, ...children);
}

function app() {
  const [text, settext] = react.usestate(
    "(my text (is here and) i want (to highlight (something here)))"
  );
  return (
    <div classname="app">
      <input value={text} onchange={(e) => settext(e.target.value)} />
      <br />
      <brackethighlighter text={text} />
    </div>
  );
}

reactdom.render(<app />, document.getelementbyid("root"));
.l1 {
  background-color: orange;
}

.l2 {
  background-color: lightgreen;
}

.l3 {
  background-color: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>


Related Query

More Query from same tag