Home > OS >  how to add html tags inside jsx (ReactJS)
how to add html tags inside jsx (ReactJS)

Time:07-30

I'm trying to put a html tag inside a span to give some styling to a certain word. but it results in a plain text instead.

expectation:

abc AND xyz

what I get instead:

abc <strong>AND</strong> xyz

here's my code: ( codesandbox )

import { useState } from "react";

export default function App() {
  const [isLoading, setIsLoading] = useState(false);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <span>{isLoading ? "abc" : `abc <strong>AND</strong> xyz`}</span>
      </div>
    </div>
  );
}

CodePudding user response:

You can just add it like this

<span>{isLoading ? "abc" : (<>abc <strong>AND</strong> xyz</>)}</span>

CodePudding user response:

One issue with your approach is that there are multiple adjacent DOM nodes. You can wrap them using a fragment:

<>abc <strong>AND</strong> xyz</>
  • Related