Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 365
Dostonbek Oripjonov Avatar asked Oct 02 '19 11:10

Dostonbek Oripjonov


People also ask

How do you add an element to a JSX element?

To concatenate JSX elements into an array in React: Initialize an empty array. Use the push() method to push JSX elements into the array. Set the key prop on the outermost JSX element to a unique value.

Can I use document createElement in react?

In React, you won't be using document. createElement .


Video Answer


3 Answers

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>
like image 75
nouvist Avatar answered Oct 25 '22 16:10

nouvist


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>
like image 28
Phillip Avatar answered Oct 25 '22 16:10

Phillip


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);
like image 38
mangart Avatar answered Oct 25 '22 15:10

mangart