skip to Main Content

Wondering if there’s any way of doing this? I think I could do it if I use dangerouslySetInnerHTML but ideally I’d just call this within my p tag.

This is my Json

  "login": [
    {
      "title": "Hello!",
      "blurb": "This is a secret direct link to enable login without a username and password. If you're having trouble accessing my portfolio via this link, please <a href="mailto: [email protected]" className={`${styles.link}`}>contact me.</a>"
    }
  ]

And then in my js file (nextJS) I’d just do this

<p className={`${styles.body} fadeIn`}>{cms.blurb}</p>

Any way of doing this? Something I can change in my json file? Trying the above results in the HTML just being appended to the string. DangerouslySetInnerHTML works, but I believe we should try avoid that?

2

Answers


  1. You can use html-react-parser for this. Simply install the package and import it in your component as:

    import parse from 'html-react-parser'; 
    

    and then in your html use it as:

    <p className={`${styles.body} fadeIn`}>{parse(cms.blurb)}</p>
    
    Login or Signup to reply.
  2. If you really can’t help but inject html via code, be aware that you have to provide to dangerouslySetInnerHTML an object containing the __html key, precisely because it’s so dangerous. So it’d be something like

    function YourLogin()   {
        return <p dangerouslySetInnerHTML = {'__html': cms.blurb}/>;
    }
    

    I cannot, however, suggest this method without reservation, as it could lead to XSS. At a minimum, make sure to validate and sanitize every input that is not safe (spoiler, it’s almost everything) to defend yourself the best you can.

    If you do not have dynamic content, you should not overcomplicate things. If you really need something to appear or disappear when something occurs, try to respond to events or use js and play with the visibility attribute or disable an element altogether.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search