Search code examples
javascriptreactjsobjectcomponentsreact-props

Add style to specific part of string in an Object prop in ReactJS


Here, the desc key has a value which is a string;

const kataData = {
  name: "Katarina",
  img: "https://ddragon.leagueoflegends.com/cdn/img/champion/splash/Katarina_0.jpg",
  desc: "The Sinister Blade, Passive: Voracity",
};

This is passed as a prop to my React component as so:

// component to hold vars
const Champ = (props) => {
  const {name, img, desc} = props;
  return (
    <div className="SmartApp">
      <h2>{name}</h2>
      <img src={img} alt={name} style={{width: "300px"}} />
       
      // here {desc} = props.desc
      <p>{desc}</p>


    </div>
  );
};

// main App
export default function ChampApp() {
  return (
    <div className="App">
      <h1>Champs Ranked</h1>
      <Champ name={kataData.name} img={kataData.img} desc={kataData.desc} />
    </div>
  );
}

So here, kataData.desc is set to pass the string directly to my component and the text shows up as expected on my site.

What i can't seem to find out is how to change certain Html elements inside this string, for example, making a section of the string bold like so:

desc: "The Sinister Blade, <b> Passive: </b> Voracity"

any tag (like the <b>) directly translates as plain text and I seem can't figure out how to separate a section of the string out to make changes the I normally would with a <span> tag.

any help is appreciated, thanks in advance


Solution

  • You can make use of innerHTML to display the strings HTML.

    1. Change the <p> tag:
    <p id="champ_desc"></p>
    
    1. Create a function to insert HTML:
    function _renderDesc(){
      let _ele = document.getElementById('champ_desc');
      _ele.innerHTML = desc;
    }
    
    1. Call this function on componentDidMount or by using useEffect:
    useEffect(() => {
      _renderDesc();
    }, []);