0

I am sorry if my question is silly, I am fairly new to Reactjs,

Please do not tell me to useHooks as I can't use it in my current project.

I am working on a form and on it's validations.

my relevant code:

//part of my state
    this.state = {
      form: {
        country: null,
        zipCode: "",
      },
      formErrors: {
        country: null,
      },
      countryList: Array<string>(),
    };
  }

       <Select name="country" defaultValue={countryOptions[1]}  options={countryOptions} value={form.country} onChange={(e) => {
                      this.handleCountryChange({value : e.value, label: e.value })
                    }}
    
                    />
                    {this.state.formErrors.country && (
                      <span className="err">{this.state.formErrors.country}</span>
                    )}

    
    
     handleCountryChange(e : countrySelection){
        const selectedCountry = e.value;
        console.log(selectedCountry);
        var formAux = { ...this.state };
        formAux.form.country = selectedCountry;
      
      }

but sadly my select keeps looking like this:enter image description here

Even after I pick a country and I can see it with the console log above. What is missing here in order for the select to pick up the value?

Ana S.
  • 23
  • 2

2 Answers2

0

You have to do this something like this

How to set a default value in react-select

Here they did not use defaultValue property

As well as check other properties which they used.

As well as refer this answer of this question too

react select not recognizing default value

0

You are not setting the state correctly, you can not mutate the state like that. You need to use setState API. See docs: https://reactjs.org/docs/react-component.html#setstate

In your case the event handler should be like this:

 handleCountryChange(e : countrySelection){
    const selectedCountry = e.value;
    // you said this works correctly
    console.log(selectedCountry); 
    this.setState(currentState => ({
        // spread the entire state so that other keys in state remain as they are
        ...currentState,                
        form: {
            // spread state.form so that other keys in state.form remain as they are
            ...currentState.form,  
            // only update state.form.country     
            country: selectedCountry
        }
    }));
 }

Please read the code comments, that should help you understand.

mehamasum
  • 4,344
  • 2
  • 16
  • 28