Ben
Ben

Reputation: 5414

Is it possible to add JSX to React code dynamically

Say I wanted to create a tree of JSX tags dynamically inside of a Javascript function, and then add them to my React code. Is that possible? If so, how would you do it?

EDIT: I am receiving <div className="msg"><p>Hello World</p></div> as a String, so I can't just return it without the quotation marks. Also, not using dangerouslySetInnerHTML.

JSX Factory

function jsxFactory() {
  return '<div className="msg"><p>Hello World</p></div>'
}

React Code

render() {
  render(
    {jsxFactory()}
  )
}

Upvotes: 1

Views: 294

Answers (2)

Dave Newton
Dave Newton

Reputation: 160191

If you explicitly need to inject HTML embedded in a string you'll need dangerouslySetInnerHtml, roughly:

function createMarkup() {
  return {__html: '<div className="msg"><p>Hello World</p></div>'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Upvotes: 0

zurfyx
zurfyx

Reputation: 32767

You can do it without the quotes.

return <div className="msg"><p>Hello World</p></div>

Upvotes: 1

Related Questions