Create multiple React Elements using one function

Asked
Active3 hr before
Viewed126 times

10 Answers

multipleelementsfunctioncreateusingreact
90%

For your grid generator, this way you can generate elements and using them in render function:,Making statements based on opinion; back them up with references or personal experience., Stack Overflow Public questions & answers

Something like:

class Grid extends Component {
  render() {
    return [...Array(this.props.items)].map((_x, i) => (
      <div
        key={i}
        style={{
          position: "absolute",
          top: i * 50,
          height: 1,
          width: "100%",
          backgroundColor: "#bfd8e0"
        }}
      />
    ))
  }
}

export default Grid;
class MainPage extends Component {
  render() {
    return(
      <div>
        <Grid items={50} />
      </div>
    )
  }
}
class MainPage extends React.Component {
  render() {
    return(
      <div>
        <Grid items={50} />
      </div>
    )
  }
}

class Grid extends React.Component {
  render() {
    return [...Array(this.props.items)].map((_x, i) => (
      <div
        key={i}
        style={{
          position: "absolute",
          top: i * 50,
          height: 1,
          width: "100%",
          backgroundColor: "#bfd8e0"
        }}
      />
    ))
  }
}

ReactDOM.render(<MainPage />, 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>
load more v
88%

React.Fragment is not that difficult to implement. We can make an empty component and get the same result.,In Vue and React, we can only render one element. Even if we have multiple elements to render, there can only be a single root element. This means if we want to render two or more elements, we have to wrap them in another element or component. Commonly, the element used for this is a <div> tag. It doesn't make much of a difference to the page structure, so a div is a popular wrapper element.,There is a new short syntax available which you can use for Fragments:

Pretag
 Pretag team - issue, fix, solve, resolve
72%

The way out is making use of a wrapper div or span element that acts as the enclosing tag. Essentially, React sees the render method outputting a single DOM node with multiple child elements inside. ,This guide explores an easy approach to render many HTML elements in React.js through React fragments. ,Wrap your JSX in an enclosing <React.Fragment> tag .

1class Countries extends React.Component {
2  render() {
3    return (
4      <li>Canada</li>
5      <li>Australia</li>
6      <li>Norway</li>
7      <li>Mexico</li>
8    )
9  }
10}
load more v
65%

When writing JSX in React, there’s one caveat: you must return one parent item. Not more than one.,However this introduces a problem - there’s an HTML element that was introduced just to make our JSX work, not necessary in the resulting HTML, but that’s where it ends into.,Another solution is to use Fragment, a relatively new React feature that solves the problem for us:

const Pets = () => {
  return (
    <Dog />
    <Cat />
  )
}
load more v
75%

Until React 16 it was required that a render method returns a single React element. With React 16 it is possible now to return an Array of elements.,Here you can see an app rendering a list of fruits. In React 16, it's now possible to extend this list with a component containing multiple new entries. Let me demonstrate this by creating a function component, fruits, a simple transitive array of multiple list elements.,Is this a new syntax in arrow functions returning arrays?

Yes, the return is implied, but it is the same as:

const Fruits = () => {
   return [];
}
40%

Let's create a simple Avatar component which shows a Facebook page picture and name using the Facebook Graph API.,So far, we've looked at how to write a single component to display data and handle user input. Next let's examine one of React's finest features: composability.,When you create a React component instance, you can include additional React components or JavaScript expressions between the opening and closing tags like this:

var Avatar = React.createClass({
  render: function() {
    return (
      <div>
        <PagePic pagename={this.props.pagename} />
        <PageLink pagename={this.props.pagename} />
      </div>
    );
  }
});

var PagePic = React.createClass({
  render: function() {
    return (
      <img src={'https://graph.facebook.com/' + this.props.pagename + '/picture'} />
    );
  }
});

var PageLink = React.createClass({
  render: function() {
    return (
      <a href={'https://www.facebook.com/' + this.props.pagename}>
        {this.props.pagename}
      </a>
    );
  }
});

ReactDOM.render(
  <Avatar pagename="Engineering" />,
  document.getElementById('example')
);
load more v
22%

To avoid array notation and manually added keys to each of the element, you can use an Aux helper function that simply returns all its children. Like so…,The basic way is to return an array of elements. To avoid warnings you have to add a key to each element, although it may not be needed in the future.,Of course. It is another really good use case. bunch of <li> elements inside a list can be another one. I can think of hundreds of them. Hopefully I explained the concept well and developers will take it from here…

const App = () => [
<p key="1">React 16 can return multiple elements ❤️</p>,
<p key="2">React 16 can return multiple elements ❤️</p>,
<p key="3">React 16 can return multiple elements ❤️</p>,
];
load more v
60%

For example, we can create an App component that renders Welcome many times:,The simplest way to define a component is to write a JavaScript function:,For example, consider this Comment component:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
load more v
48%

Multiple Components with Keys,Rendering Multiple Components,Unique Component Keys

NumberList (props) => {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

const numbers = [1, 2, 3, 4, 5];

ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);
load more v
23%

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.,Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form.,Box.js: It is responsible to show each box with its proper height, width, color set in the background. 

Other "multiple-elements" queries related to "Create multiple React Elements using one function"