React giving a style to particular part of the string before rendering?

Viewed 40

I want to build a pokemon search box that displays suggestion pokemons while the user types in. Now that works but I also want to highlight the searched text when displaying the whole pokemon name.

So I basically want to replace plain searchedText with colored text. I tried to replace it like this below and in some other ways but I couldn't make it work. It shows [Object object]<remaining text>

And the text would be in the beginning, middle, or at the end.

 const PokemonProfile = ({name, searchedText}) => {
        
        const fullStr = name.replace(searchedText, <span style='background-color: rgba(0, 255, 0, 0.3)'> {searchedText} </span>)
        
        return (
            <div>
                <h4 className='PokemonProfile'> {fullStr} </h4>
            </div>
        )
    }

What would be the best implementation of it? Any suggestion is appreciated

2 Answers

Assuming searchedText is a string, and it always shows up exactly once in name.

const PokemonProfile = ({
  name,
  searchedText
}) => {
  const [before, after] = name.split(searchedText);

  return ( 
    <div>
      <h4 className="PokemonProfile">
        <span>{before}</span>
        <span style={{ backgroundColor: "rgba(0, 255, 0, 0.3)" }}>
          {searchedText}
        </span>
        <span>{after}</span>
      </h4>
    </div>
  )
}

Split your text into 3 parts:

const PokemonProfile = ({name, searchedText}) => {
  const start = name.indexOf(searchedText);
  const end = start + searchedText.length;
  const firstPart = name.substr(0, start);
  const lastPart = name.substr(end);
        
  return (
    <div>
      <h4 className='PokemonProfile'>
        <span>{firstPart}</span> 
        <span style={{ backgroundColor: "rgba(0, 255, 0, 0.3)"}}>{searchedText}</span>
        <span>{lastPart}</span>
      </h4>
    </div>
  )
}
Related