HTML Parser - danberkeland/personalReddit GitHub Wiki
install the add-on:
yarn add react-html-parser
In the Reddit API I was able to find the attribute that held the post data as an escaped HTML string. A mess of ampersands and semicolons that needed to be translated into something readable by react. I found 'react-html-parser' to do the trick. But the steps to do it weren't so intuitive. First I imported the module:
import ReactHtmlParser from 'react-html-parser';
const translate = (text) => {
let fin = text.replace('<!-- SC_OFF -->','').replace('<!-- SC_ON -->','').replace('class="md"','');
let finfin = ReactHtmlParser(fin)
return finfin[0]
}
const translate2 = (text) => {
let fin = text.replace('<!-- SC_OFF -->','').replace('<!-- SC_ON -->','').replace('class="md"','');
let finfin = ReactHtmlParser(fin)
if (finfin[0].endsWith('.jpg')){
return "<img src='"+finfin[0]+"'/>"
I created two functions. One to parse a string and return an HTML string. The other to return a jpeg if it exists. Looking at it now, this could easily be combined into one function. First, it peels off some useless string scraps. Next it parses the HTML. This returns an array with one string. That's why it's necessary to add the [0]. The second function checks to see if the string is a jpg location. If so, it returns it as a call to an image source.
The render that calls these functions is below:
<main>
{items.map(item => (
<React.Fragment>
<article>
<Karma karma={item.data.score}/>
<div className="postInfo">
<h2>{item.data.title}</h2>
{item.data.selftext_html ? <React.Fragment>{ReactHtmlParser (translate(item.data.selftext_html))}</React.Fragment> : <p>{item.data.selftext}</p>}
{item.data.url ? <React.Fragment>{ReactHtmlParser (translate2(item.data.url))}</React.Fragment> : <p>{item.data.selftext}</p>}
<Footer author={item.data.author} commentCount={item.data.num_comments} timePosted={item.data.created_utc}/>
{/* <Comment /> */}
</div>
</article>
</React.Fragment>
))}
{/* <button>BACK TO LIST</button> */}
</main>
The part concerning the parsing is here. For some reason I needed to add ReactHtmlParser a second time for it to work. No idea why:
{item.data.selftext_html ? <React.Fragment>{ReactHtmlParser (translate(item.data.selftext_html))}</React.Fragment> : <p>{item.data.selftext}</p>}
{item.data.url ? <React.Fragment>{ReactHtmlParser (translate2(item.data.url))}</React.Fragment> : <p>{item.data.selftext}</p>}