4

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
  • 1,817
  • 3
  • 13
  • 12

2 Answers2

5

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.

MattYao
  • 2,495
  • 15
  • 21
0

I cannot write the format_string function in jsx for some reasons is there any way around this ?

Yes, You actually can, but I think You are not sure how ;)

Just create a helper function which will return text inside b tag - if content is defined.

class MyComponent extends Component {
  ...
  render() {
    {renderContent(content)}
    ...
  }
}

const renderContent = (content) =>
  content && <b>{contnet}</b>
grzesiekgs
  • 463
  • 2
  • 11
  • yeah 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 Mar 13 '17 at 12:26
  • Well, 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. – grzesiekgs Mar 13 '17 at 12:38