React JSX append HTML (react object) after initialization
If you need to use HTML and escape React, just use a ref
which is like a persistent DOM node across renders. I'm unsure how often or if you would have to re-append DOM nodes after a legitimate render/update.
The best pattern is to get as close to a PureComponent as possible. A PureComponent renders HTML purely off props -- no update lifecycle logic.
In the future, internal state will be considered an anti-pattern (separation of model and view allows for data handoff between platforms/devices, and for different skins to render the same stuff).
render () {
return (
<div className='container'>
{this.userCards()}
</div>
);
}
userCards () {
if (this.props.users) {
return this.props.users.map(user => this.userCard(user));
}
}
userCard (user) {
if (user) {
return (
// React may complain to use key={user.id} for tracking and mutating items
<div className='card'>
{user.name}
</div>
);
}
}
Some people prefer userCardsTemplate()
, userCardsUI()
, renderUserCards()
etc
do something like this
render () {
var users = this.state.users,
var usersDiv = [];
for (var i = 0; i < users.length; i++) {
var temp = (<div>{users[i]}</div>);
usersDiv.push(temp);
}
return(
<div>
{usersDiv}
</div>)
}
this would return you a div with multiple users div based on your JSON.
Put your children into a normal array and then use {}
to put that array inside your div element (i.e. create the div element after the array). That keeps it immutable. Adding children to it afterwards seems very un-React-y to me.
Sorry for misreading the question. What you're looking to do can be achieved with the "portals" pattern described by Ryan Florence & Michael Jackson here. Below is an attempt at solving what I believe is your question. Forgive me if I'm still not understanding your question.
render() {
// dont render anything, open a "portal"
return <div ref="container" />;
}
componentDidMount() {
// get initialized component markup
var container = this.refs.container;
var cards = [];
for (var i = 0; i < users.length; i++) {
cards.push(this.createCard(users[i]));
}
// start a new React render tree with the container and the cards
// passed in from above, this is the other side of the portal.
ReactDOM.render(<div>{cards}</div>, container):
}