Rendering JSX From Strings

Jimmy Cheung
2 min readSep 7, 2020

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.

Sources

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response