React js render html string returned from server
10,431
You can use dangerouslySetInnerHTML attributes to render your html strings.
Check React doc (https://facebook.github.io/react/docs/dom-elements.html) for more details.
Author by
IMOBAMA
Updated on June 08, 2022Comments
-
IMOBAMA almost 2 years
From php im returning this html
PHP
$str = "Hello World"; echo json_encode("returnval"=>format_string($str)); function format_string($str){ return "<b>".$str."</b>"; }
React JSX
render () => { //returnval = html string returned from php return ( <div> {returnval} <div> <span>Some data</span> </div> </div> ); }
The above prints
<b>Hello World</b>
as a text .But i want the html tags to be executed (in this case as bold)
I cannot write the
format_string
function in jsx for some reasons is there any way around this ? -
IMOBAMA about 7 yearsyeah i know that i can lol.. but in reality my
format_string
is very complex function(uses lots of dependencies too ) . this was just an example. obviously i can write it in javascript but i wanted a quick solution. thanks anyways -
IMOBAMA about 7 yearsyea it works ........
-
grzesiekgs about 7 yearsWell, short and reasonable answer is just don't do it. When You dangerously inject HTML into React component, it cannot be handled by virtual DOM, so each time it changes, it has to be replaced instead of updated. You say that Your HTML is quite complex, so it is safe to assume that such a "feature" is performance killer.