How to insert Bold tags into a template literal string in react and typescrip

Viewed 5168

I have a form that appears when a button is pressed, the heading of the form will be different for each item in a list, I can remove these items. I would like the name of the item in the form heading to be bold but I am struggling to implement this correctly

my form looks like

render(): React.ReactNode {

 return (
  <FormGroup
    fieldId='example-form
    helperText={`do you want to delete <b>${this.props.item.name}</b>?`
    >
    </FormGroup>
   )
  }

this currently prints out the <b> tags. I have tried assigning this.props.item.name to a variable as a string and using bold() on that but it didn't work. Any advice would be appreciated.

2 Answers

You can't embed html in a string, which is a security feature of React to prevent cross site scripting when displaying user provided content.

But, what you actually have here is JSX!

So change the helperText type to React.ReactNode and now you can pass in a fragment like so:

<FormGroup
  fieldId='example-form'
  helperText={
    <>
      do you want to delete <b>{this.props.item.name}</b>?
    </>
  }
/>

Passing of HTML tag inside template literals is not allowed. It will render your HTML tag as a string. To solve it, you can create a JSX variable for your help text and pass that to your helperText prop in FormGroup element.

render(): React.ReactNode {
 const helperText = <>do you want to delete <b>{this.props.item.name}</b></>;

 return (
   <FormGroup
    fieldId='example-form'
    helperText={helperText}
   >
   </FormGroup>
  )
}
Related