lundi 23 novembre 2020

setState inside for loop doesn't update state correctly

I have 3 divs. Every one will have class active when I click in specific button. Every div of them has a state variable whenever it's true I add className='active' to the div connected to it:

When I click on the button the state changes but the div doesn't get class active

async activeLang(e) {
    let lang = e.target.getAttribute('lang');

    for (const key in this.state.status) {
      await this.setState(state => {
        state.status[key] = false
      })
    }

    this.setState(state => {
      state.status[lang] = true
    })

    console.log(this.state.status);
  }

================================================

<ul>
 <li lang="en" onClick={this.activeLang} className={this.state.status.en ? 'active' : '' }>EN</li>
 <li lang="ar" onClick={this.activeLang} className={this.state.status.ar ? 'active' : ''}>AR</li>
 <li lang="fr" onClick={this.activeLang} className={this.state.status.fr ? 'active' : ''}>FR</li>
</ul>

================================================

<div className={this.state.status.en ? 'to-input en active' : 'to-input en'}>
 <input required type='text' onKeyUp={this.onInputChange} />
 <label title='Category name' placeholder='Ex. Business Cards'></label>
</div>

<div className={this.state.status.ar ? 'to-input ar active' : 'to-input ar'}>
 <input required type='text' onKeyUp={this.onInputChange} />
 <label title='اسم الفئة' placeholder='مثال: كروت العمل'></label>
</div>

<div className={this.state.status.fr ? 'to-input fr active' : 'to-input fr'}>
 <input required type='text' onKeyUp={this.onInputChange} />
 <label title='Nom de catégorie' placeholder='Ex. Cartes de visite'></label>
</div>

fig 1




Aucun commentaire:

Enregistrer un commentaire