简体   繁体   中英

How to append child to React element

I want to append child to my main div with loop

let mainContainer = React.createElement("div", { className: "contexCon" });

like this

for(let i = 0; i < 3; i++){
    mainContainer.appendChild(child[i]) // this will not work just as example
}

TL;DR: React accepts array React Node as children.

Do your fetch API thing in componentDidMount and componentWillUnmount . "Why?" if you ask. Because, it will be more safe if you handle asynchronous task with built-in React life cycle. So, there will no unhandled fetch in your component in case the component is disappear or any like that when the fetch is complete.

But in this case, I will not use state and/or any lifecycle since my data is dummy and static.

You said loop, but I'm pretty sure that it means loop for put your data into html element. So, it will be more simple if you use Array.prototype.map() . Basically, it will loop array and callback function and get its return value as a new array.

You still could use for or while keyword too in case you didn't like this method.
EDIT: see @mangart 's answer for method that uses for keyword.

// example
const array = [2, 3, 4];
const arrayMap = array.map((val) => val * 2) // [4, 6, 8]

 class App extends React.Component { myData = [ {key: 1, name: "Hello"}, {key: 2, name: "World"}, {key: 3, name: "etc"} ]; render() { // the loop. it'll return array of react node. const children = this.myData.map((val) => ( <button id={val.key}>{val.name}</button> )); // the div with children inside return ( <div className="contexCon"> {children} </div> ); } } // render your app const rootElement = document.getElementById("root"); ReactDOM.render(<App/>, rootElement);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"/>

Function-based element and no JSX.

 function App() { // the data const myData = [ {key: 1, name: "Hello"}, {key: 2, name: "World"}, {key: 3, name: "etc"} ]; // the loop const children = myData.map((val) => ( React.createElement("button", {id: val["key"]}, val["name"]) )); // the div with children inside return ( React.createElement("div", {className: "contexCon"}, children ) ); } // render ReactDOM.render(React.createElement(App, {}), document.getElementById("root"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"> <style>.contexCon {background-color: yellow; margin: 8px 0;}</style>

React.createElement has a signature like this:

React.createElement(
  type,
  [props],
  [...children]
)

So the third parameter should be an array of your children. In your example it seems like you could just do:

let mainContainer = React.createElement("div", { className: "contexCon" }, child);

 const headline = React.createElement('h1', {}, 'Hello, World;'). const body = React,createElement('p', {}; 'Lorem ipsum dolor sit amet'). const X = React,createElement('div', {}, [headline; body]). ReactDOM,render(X. document;getElementById('app'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

I just had the same problem of appending child elements to a parent element. How I solved this problem was to create the child elements and add them to an array before creating the parent element. And then when you create the parent element, you just pass it the before created array of child elements. So in your case the code for 5 child div elements would look something like this:

var elements = [];
for(let i = 0;i < 5;i++){
    elements.push(React.createElement("div",null));
}
let mainContainer = React.createElement("div", { className: "contexCon" },elements);

Also if you want to use a DIV element for show messages like a console, the best way is using pure javascript like this:

consoleMessage = (text_msg) =>
{        
    let parr = document.createElement('p');
        parr.setAttribute('class','message');
        parr.innerHTML = text_msg;
    
    let consoleLine = document.getElementById("Console");        
    
        consoleLine.appendChild(parr);   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM