VonAxt
VonAxt

Reputation: 95

How to create multiple tags in React based on value passed through props

how can I create multiple elements based on the value passed in props or initial state.

constructor(props, context) {
    this.state = {
        numberOfElements: this.props.numberOfElements || 6
    }

render() {
    return (
        <div>
            {/*Six elements if not passed through props*/}
            span
            span
            ...
            span
        </div>
   )
}

Is there React.method available for this purpose?

Upvotes: 0

Views: 1540

Answers (3)

GYTO
GYTO

Reputation: 500

This is probably the cleanest one with ES6

render() {
    return (
        <div>
            {[...Array(4).keys()].map(i => <span key={i}/>)}
        </div>
   )
}

Upvotes: 0

Sagiv b.g
Sagiv b.g

Reputation: 31024

You should use arrays to iterate and create elements.
One way could be:

render() {
    const myArray = new Array(this.state.numberOfElements).fill('bar'); //  array with 6 members ("bar")
    return (
        <div>
            {myArray.map(i=><span>foo</span>)}
        </div>
   )
}

Running example:

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      numberOfElements: this.props.numberOfElements || 6
    }
  }
  render() {
    const myArray = new Array(this.state.numberOfElements).fill('bar');
    return (
      <div>
        {myArray.map(i => <div>foo</div>)}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Upvotes: 1

Prakash Sharma
Prakash Sharma

Reputation: 16472

Use array of elements to render multiple elements

constructor(props, context) {
    this.state = {
        numberOfElements: this.props.numberOfElements || 6
    }

renderElements(){
  let elements = [];
  let total = this.props.numberOfElements || this.state.numberOfElements;
  for(let i = 0;i < total;i++){
     elements.push(<span>Hello</span>)
  }
  return elements;
}

render() {
    return (
        <div>
            {this.renderElements()}
        </div>
   )
}

Upvotes: 1

Related Questions