Pre fill MDBSelect with state


Topic: Pre fill MDBSelect with state

gllermaly asked 6 years ago

Hello, Im using MDBSelect to an Edit form so Im receiving in props the initial values, and I need to populate this select with the value provided in props.

How can I achieve this ?.

Lets say this.props.color = 1

and select option is :

<MDBSelectOptionvalue="1">
red
</MDBSelectOption>

I dont want to load value into MDBSelectInput but pre-select the option value.

Regards


Jakub Mandra staff premium answered 6 years ago

Add property 'selected' to preselect option :)

But, as i assume that, you want to change selected options after everything has mounted.
In this situation you have to use alternative Select component with object as a datata source - it has the ability to react on properties updates. 


gllermaly answered 6 years ago

@Jakub Mandra Thanks! , but in that object I only see "value" option that in reality is "text" option.

To determinate if option is selected or not I need to compare values, not texts (labels) because my field value is "days" (int) and my text is "X days"

I dont want to create a dirty solution where Im parsing strings.
I  hope you follow me 

EDIT:
I will try when I come back  home to just pass a "dbValue" attribute to option object, should work right?

This did the job, if you know a cleaner way let me know please 

optionsExample = [ { dbValue:3 , value: "3 days"} ]

  componentWillMount() {

//dummy database object

const dbObject = { days: 3 };

let optionsSelect = this.state.options;

optionsSelect.map(opt => {

if (opt.dbValue === dbObject.days) opt.checked = true;

});

this.setState({ options: optionsSelect });

}

Jakub Mandra staff premium answered 6 years ago

Here is the options object example from our documentation:

options: [
{
checked: false,
disabled: false,
icon: null,
value: "Option one"
},
{
checked: false,
disabled: false,
icon: null,
value: "Option two"
},
{
checked: true,
disabled: false,
icon: null,
value: "Option three"
},
{
checked: false,
disabled: false,
icon: null,
value: "Option four"
}
]

 

My suggestion how to build an object with preselected options:

componentDidMount() {

const preselected = this.state.options.map(opt => {

return {

...opt,

checked: opt.dbValue === this.state.dbObject.days

}

});

this.setState({ options: preselected });

}

 


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue
  • User: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 4.7.1
  • Device: PC
  • Browser: Chrome
  • OS: Ubuntu 16
  • Provided sample code: No
  • Provided link: No