Reactjs - if condition inside the map

Asked

Viewed 456 times

0

I have a requisition for the states

api.get('address/states')
  .then(res => {
      const states = res.data.data;
      this.setState({ states });
  })

And another that searches the address data by the zip code and fills in the form pain fields:

CheckZipcode() {
    let cep = this.state.zipcode.substring(0, 9);
    api.post('address/zipcode', { cep })
        .then(res => {
            const address = res.data.data;                
            this.setState({ neighborhood: address.bairro });
            this.setState({ city: address.cidade });
            this.setState({ complement: address.complemento });
            this.setState({ street: address.endereco });
            this.setState({ uf: address.estado });
            this.setState({ id_city: address.id_cidade });
            if (address) {
                api.get(`address/cities/${this.state.uf}`)
                    .then(res => {
                        const cities = res.data.data;
                        this.setState({ cities });
                    })
            }
        })
}

I have a select that is populated with the data of the first request. I need that when the user enters the ZIP code the select be selected. I tried to do so:

{this.state.states.map((estado, i) =>
    {
        if(this.state.uf === estado.uf){
            <option selected value={estado.uf} label={estado.estado} key={i} />
        } else{
            <option value={estado.uf} label={estado.estado} key={i} />
        }
    }
)}

But then the map doesn’t render the state data. If I put as below, it shows but I can’t do the validation if the user has typed the zip code:

{this.state.states.map((estado, i) =>
    <option value={estado.uf} label={estado.estado} key={i} />
)}

  • 1

    In the example that does not work you are using map without return. In the second example you do not need return because it doesn’t have a block of {}.

1 answer

1


    if(this.state.uf === estado.uf){
        **return** <option selected value={estado.uf} label={estado.estado} key={i} />
    } else{
        **return** <option value={estado.uf} label={estado.estado} key={i} />
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.