5

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 ?

2
  • Do you get any errors? Commented Mar 13, 2017 at 12:17
  • @DeividasKaržinauskas no errors.. i just want the html to be printed as html and not as text Commented Mar 13, 2017 at 12:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yea it works ........
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>

2 Comments

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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.