Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JSX append HTML (react object) after initialization

How do I make this function work, appending to my react object between initialization and return

render () {
    var users = this.state.users,
        appContainer = <div id="container"></div>

    for (var i = 0; i < users.length; i++) {
        // this doesn't work
        appContainer.appendChild(this.createCard(users[i]));
    }

    return appContainer;
}
like image 315
neaumusic Avatar asked Jul 04 '16 21:07

neaumusic


People also ask

Does JSX allows us to write HTML in React?

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

Can you put JSX in object?

Yes you can. JSX gets compiled to objects so you'll have an array of objects representing React elements.

Can I add a React component to HTML?

Step 1: Add a DOM Container to the HTML This will allow us to find it from the JavaScript code later and display a React component inside of it. You can place a “container” <div> like this anywhere inside the <body> tag. You may have as many independent DOM containers on one page as you need.


2 Answers

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):
}
like image 161
evkline Avatar answered Oct 11 '22 10:10

evkline


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.

like image 29
John Peter Avatar answered Oct 11 '22 10:10

John Peter