Steven
Steven

Reputation: 4963

Pushing elements to array

From what I have been able to gleam from the Internet, this function should work. However, babel fails to compile it citing a invalid token. If I comment out the push lines everything works.

Can someone help me out with the correct syntax to do this?

renderSuggestionText(highlightText, text) {
  const fragments = [];

  let buffer = text;
  while (buffer.length > 0) {
    const fragmentStart = text.toUpperCase().indexOf(highlightText.toUpperCase());
    if (fragmentStart > 0) {
      fragments.push(<span>{buffer.substr(0, fragmentStart)}<span>);
      fragments.push(<span className="bold">{buffer.substr(fragmentStart, highlightText.length)}</span>);

      buffer = buffer.substr(fragmentStart + highlightText.length);
    } else {
      fragments.push(<span>{buffer}<span>);
      buffer = '';
    }
  }

  return fragments;
}

Upvotes: 1

Views: 62

Answers (1)

jmancherje
jmancherje

Reputation: 6633

There is a syntax error on some of the span tags. You need to make sure you close all of your tags (<span></span>) For example:

} else {
  fragments.push(<span>{buffer}<span>);
  buffer = '';
}

Babel will always throw an error if you fail to close all of your tags. Should be something like "Unterminated JSX .."

should read:

  fragments.push(<span>{buffer}</span>);

Upvotes: 2

Related Questions