Amrmsmb
Amrmsmb

Reputation: 11416

How to create array of buttons inside a loop

I am trying to create array of buttons as shown below in the code section. I am using sandbox. I'm getting the error posted below

code:

import React from "react";
import ReactDOM from "react-dom";
import createReactClass from "create-react-class";

var arrButtons = [];
var buttonStyle = {
    margin: '10px 10px 10px 0'
};

class ButtonClicks extends React.Component {
    constructor(props) {
        super(props);
        this.onClickFunction = this.onClickFunction.bind(this);
    }
    onClickFunction() {
      console.log("hello world from button: " + i);
    };

    render() {
        return (
            for (let i = 0; i < 10; i++) {
                var button = <button
                    style={buttonStyle}
                    onClick={onClickFunction}>
                    p.name
                </button>
                arrButtons.push(button);
            }
        );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<ButtonClicks />, rootElement);
export default ButtonClicks;

error

/src/index.js: Unexpected token (21:4)

Upvotes: 1

Views: 2882

Answers (1)

ionizer
ionizer

Reputation: 1721

Your approach is correct. BUT! React's render only accepts 1 element (which child can have as many elements as you need it). So you need to wrap those buttons inside a div. That's about the only change I made aside of moving your for loop outside return.

var arrButtons = [];
var buttonStyle = {
    margin: '10px 10px 10px 0'
};

class ButtonClicks extends React.Component {
  constructor(props) {
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  
  onClick() {
    console.log("hello world");
  }

  render() {
    for (let i = 0; i < 10; i++) { //Moved your loop outside render()'s return
      arrButtons.push(<button style={buttonStyle} onClick={this.onClick}>{i}</button>)
    }
    return (
      <div>
        {arrButtons} {/*Very important to wrap the buttons inside a div*/}
      </div>
    );
  }
}

ReactDOM.render( <ButtonClicks/> , 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

Related Questions