Rendering JSX From Strings
In building my Slay the Spire app, we created an API that delivered description strings that already had prewritten JSX. This was done so that we could implement keyword tooltips without having to parse the descriptions on the client end.
However, we ran into a problem — the strings were not being translated into JSX after we piped the prewritten JSX into the React component. Here is an example of that prewritten JSX:
<Keyword name="Exhaust"></Keyword> your hand.\nDeal 7 damage for each card <Keyword name="Exhausted"></Keyword>.\n<Keyword name="Exhaust"></Keyword>."
The problem with this is that React would not recognize this as JSX when it was a string piped in from our API. It would show up as simple HTML and would not recognize those keyword names.
After experimentation with different methods, we decided to use a plugin we found called ‘react-html-parser’:
Using this plugin, we were able to pass our marked up strings into a prewritten function that allowed us to create JSX.
Here is how we did it:
First, we installed this package:
npm install react-html-parser --save
Then, we imported the library and created a transform function for the code:
import ReactHtmlParser from 'react-html-parser';const options = { transform }function transform(node, index) {
if (node.type === 'tag' && node.name === 'keyword'){
return
<Keyword key={index} name={node.attribs.name}
keywords={props.keywords}/>; } }
The code simply will transform any node that has a type of “tag” that is named “keyword”. It will recognize the marked up JSX that we created and return a proper JSX component.
In the render/return output of the component, you can then just input the string of marked up text with the options set up in the above code:
ReactHtmlParser(props.card.attributes.keyword_description, options)
This way, you can prewrite/markup some JSX code from your API and then use it in your React components with minimal fuss.