0

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.

2
  • Can you also post an example of the 'allChapters' array here? Commented May 4, 2021 at 8:59
  • Tough not the problem here, but why this.setState(({ currentChapter }) => ({ currentChapter: chapNum }))? For your case: this.setState({ currentChapter: chapNum }) would suffice. Commented May 4, 2021 at 9:03

2 Answers 2

2

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

1
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.