0

Code Snippet:

function Button(props) {
  var ans = [
    ["56","30","11","20"],["1","-2","2","-1"],
    ["odd","even","none","both"]
  ];
  var button = [], i;
  for(i = 0; i <= 3; i++) {
    button.push(<button key={i} onClick={()=>props.ind(i)}>
                  {ans[props.q-1][i]}
                </button>)
  }
  return (<div>{button}</div>)
}

I am a newbie at using fatarrows and react.I am making a quizzing interface.Here each of the four buttons (i=0 to 3) holds a choice for a specific question no.(q) On checking web devs i found that for each of the 4 buttons,value of i passed in props.ind method is 4,i.e value of i after final increment.

EJ Mason
  • 2,000
  • 15
  • 15
Biboswan
  • 1,145
  • 12
  • 15
  • It's a common mistake every JavaScript programmer has made at least once due to function scoping of variables. Have a read of this: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Phil Bellamy Jul 27 '17 at 23:11
  • Thanks @Phil Bellamy it helped – Biboswan Jul 28 '17 at 08:58

2 Answers2

1

Finally fixed it.So i is a var variable. For each of the four buttons stored in button array, value of i wasn't copied in prop.ind(i) method parameter instead the reference was stored.Hence the last value of i at the end of loop i.e 4 is what we get for each of the HTML button,props.ind(4).

Now instead when I declare let i in the for loop refernce cannot be stored since it wont be accessible outside of the loop as a result the immediate value of i is stored in props.ind.ie props.ind(0) for 1st button , props.ind(1) for 2nd button in this way.

Biboswan
  • 1,145
  • 12
  • 15
0

It's difficult to understand what you are trying to make happen. If you add more information I can help some more.

Here is some code below which can help you get started. It loops through the array of questions and then loops through answers:

const Buttons = (props) => {
  const questions = [
    ["56","30","11","20"],
    ["1","-2","2","-1"],
    ["odd","even","none","both"]
  ];

  return (
    <div>
      {questions.map((question, i) => (
        <div key={i}>
          {question.map((answer, n) => (
            <button key={n} onClick={() => alert(answer)}>
              {answer}
            </button>
          ))}
        </div>
      ))}
    </div>
  );
};

ReactDOM.render(
  <Buttons />,
  document.getElementById('app')
);
<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="app"></div>
Austin Greco
  • 32,997
  • 6
  • 55
  • 59