skip to Main Content

I am passing a long string to render in a component and I want to change the styling of some words by passing them as span. How can I achieve that in React? I am using Tailwind for CSS. I know I can pass a string array of the spans text, but I am wondering if I can do that passing only 1 string or other value type.

<Home description="How can I <span className="text-highlight">highlight</span> 
parts of <span className="text-highlight">this</span> string?" />

Component:

{description && (
  <p className="text-sm text-text">
    {description}
  </p>
)}

2

Answers


  1. I believe what you are looking for is https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html.

    You will want to do something like the following within your Home component.

    export default function Home({ description }) {
      return (
        {description && (
          <p className="text-sm text-text">
            <span dangerouslySetInnerHTML={description} />
          </p>
        )}
      )
    }
    

    Using dangerouslySetInnerHTML as its name suggests is dangerous to use. Only use on trusted or sanitized values. I would recommend reading more about this in the link.

    Login or Signup to reply.
  2. You can directly pass JSX as a prop to render.

    <Home description={<>How can I <span className="text-highlight">highlight</span> 
    parts of <span className="text-highlight">this</span> string?</>} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search