Skip to content
Advertisement

Component does update but if statement isn’t working

I’ve found a weird behavior in my react code. I’m fairly new to react and can’t figure it out.

In the past few days, I’ve created a nice dashboard and want to add a data page with CRUD transactions. I want to change the text inside the search button, when the searchForm state is true, but it does only work after the component updated, not on first rendering. I’ve initiated the searchForm state with false and on searchBtnClick the state gets set to true. But the text inside the button doesn’t change.

JavaScript

Thanks in advance, Marc

Advertisement

Answer

A couple suggestions I would make about this code:

  1. A somewhat personal preference, using arrow notation to define class methods so you don’t have to .bind(this) for every one.
JavaScript
  1. The code inside your if (this.state.error) {} is almost identical to the entire component with some minor changes. I would suggest being more targeted / specific with your if statements and just change the smallest piece needed. (see large code blow below)

  2. In a couple places you are using a ternary operator to return something OR a <Fragment />. Again, this might just be personal preference, but you could instead just use && to simplify the code some.

JavaScript

Here is your full code sample with the simplifications from above applied.

RE: your actual question though, about why the text isn’t swapping out inside your search button… your click handler looks correct and should be changing the state properly… Maybe having the if statement like I suggested, be more targeted to only changing the actual text inside the button instead of the whole button will help.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement