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
You can use html-react-parser for this. Simply install the package and import it in your component as:
and then in your html use it as:
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 likeI 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.