R-S
R-S

Reputation: 151

How to pass parameters from a button in REACTJS?

I want to show only the paragraphs related to the selected chapter. To do this I did STATE with the selected Chapter number (the chapters are in numbers) When I view the paragraphs in the page load it works fine.

I also want to make a list of buttons that move to the other chapters. The problem is that when I press the above buttons it does not change the STATE and I did console.log and really saw that the parameter I pass is incorrect. Where am I wrong in the code?

 {allChapters.map(allChapter =>
     <button key={allChapter} onClick={(allChapter) => this.handleChange(allChapter)}>
         {allChapter}
     </button>
 )}

 handleChange = (chapNum) => {
     this.setState(({ currentChapter }) => ({ currentChapter: chapNum }))
     console.log('chapNum', chapNum);
 };

console.log()

It is important to note: {allChapter} is mirror number (1,2,3, ...) and the problem is not in it.

Upvotes: 0

Views: 793

Answers (2)

hellogoodnight
hellogoodnight

Reputation: 2129

With your current code, the only thing you do is to rename the default onClick event parameter to allChapter. Just do this instead:

{allChapters.map(allChapter =>
    <button key={allChapter} onClick={() => this.handleChange(allChapter)}>
       {allChapter}
    </button>
)}

Btw, you should change the variable name allChapter to chapter ;)

Upvotes: 2

Bob Kelso
Bob Kelso

Reputation: 52

<button key={allChapter} onClick={(allChapter) => this.handleChange(allChapter)}>
  {allChapter}
</button>

By doing this, you rename the default onClick event parameter with

allChapter

Then you pass this renamed event to the handleChange. It's why, your console.log shows an event.

The correct way to pass your parameter is :

<button key={allChapter} onClick={() => this.handleChange(allChapter)}>
  {allChapter}
</button>

Upvotes: 1

Related Questions