Nieck
Nieck

Reputation: 1646

HTML tags to JSX React Native

I'm doing a call to an API that returns some HTML:

example:

<p>Hello there</p><p>Javascripti</p>

I want to use this in my React Native app but this time I want to replace all the <p> tags for <Text> because that is something I can use in React Native.

How can I achieve something like this? I can't find out how to translate or parse HTML.

EDIT: I used Regex to make the <p> a <Text> but it just returns a string. It displays this on the screen: <Text>Lorem Ipsum</Text. How can I parse this to readable JSX?

Upvotes: 3

Views: 3319

Answers (2)

Mauricio Pasquier Juan
Mauricio Pasquier Juan

Reputation: 2365

JSX is basically syntax sugar (as seen here, here and especially here) for calling createElement:

React.createElement(component, props, ...children)

So once you've captured the text inside the <p></p> tags you can generate any tag like this:

let capturedContent = 'Hello there'

const element = React.createElement('Text', { }, capturedContent)

Upvotes: 1

ShaneG
ShaneG

Reputation: 1518

Regex can be used here:

Tags changed

const myRegex = /(<p>|<\/p>)/g;
const myHtml = '<p>Hello there</p><p>Javascripti</p>';

myHtml.replace(myRegex, 'Text');

Then place this into your React-Native render for your jsx. It would be something like this. I do not know your full setup so apologies:

render() {
 return (
  {myHtml}
 )
}

Upvotes: 0

Related Questions