2

How to display javascript/html code in react.js render.

I have tried like this

var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong </p>';

return (
    <div>
        <div dangerouslySetInnerHTML={{__html: thisIsMyCopy}}>
        </div>
    </div>
)

This is html code.. but i also want to display javascript code on my screen... how i can do that.. Can you guide me.. how to proceed with it

1
  • You should never ever have to use dangerouslySetInnerHTML. I recommend you stop right away. Commented Oct 27, 2016 at 20:28

2 Answers 2

3

Its already in a stringed version, just need to include the variable inside curly braces. dangerouslySetInnerHTML is for when you want to turn a html string into actual html.

var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong </p>';

return (
  <div>
    {thisIsMyCopy}
  </div>
)

if you want a string version of a function just take whatever function and add a string to it like so:

function functionString() { console.log('stringed function") }

var functionAsString = '' + functionString

return (
  <div>
    {functionAsString}
  </div>
)

Here is a working pen demonstrating this http://codepen.io/finalfreq/pen/JRqEWW

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

2 Comments

Can you be more specific by what you mean? like stringified javascript functions? As you would see them in the code editor?
Your solution only work on simple case and does not handle backtrick, single quote and double quote and variables and ...?
-1

If you want to display the "code" in html, you can use

<code>something</code>

tag and it will display your code onto the screen.

1 Comment

But only in HTML5 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.