Topic: Control the selected option
                  
                  ahadortiz
                  free
                  asked 6 years ago
                
I use the react materia- select.Btw, I can't control the selected option.The value appears instead of the text at top if I use the 'selected' prop.Please check the screenshot.
What can I do? Here is my code:

Please help me
Thanks
                      
                      Aliaksandr Andrasiuk
                      staff
                        answered 6 years ago
                    
Hi,
selected property is setting default select text content. It doesn't add an option to your options list.  And it's displayed above all the options and can't be clicked. 
I recommend using only your options from the state. You can set checked property in the state if you need. 
If you want to add an option to options list from f.e. Input you can try the next code:
import React from "react";
import { MDBSelect, MDBInput, MDBBtn } from "mdbreact";
class App extends React.Component {
  state = {
    options: [
      {
        checked: false,
        value: "1"
      },
      {
        checked: false,
        value: "2"
      },
      {
        checked: false,
        value: "3"
      }
    ],
    inputValue: ""
  };
  addOption = () => {
    this.setState({
      options: [...this.state.options, { checked: true, value: this.state.inputValue }]
    })
  }
  onChange = e => {
    this.setState({
      inputValue: e.target.value
    })
  }
  render() {
    return (
      <div style={{ width: "500px", margin: "50px" }}>
      <MDBSelect
        options={this.state.options}
        label="Choose your option"
      />
      <MDBInput onChange={e => this.onChange(e)} value={this.state.inputValue}/>
      <MDBBtn onClick={this.addOption}>Add an option</MDBBtn>
    </div>
    );
  }
}
export default App;
After clicking on the button it will add the option to the options list in state, where value is value provided to input and checked will set to true(also can be set to false) (but don't forget to set all the others options checked  value to false if you are not using  'multiple' select).
Hope I could help.
Best regards.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Free
 - Premium support: No
 - Technology: MDB React
 - MDB Version: 4.14.0
 - Device: PC
 - Browser: google chrome
 - OS: Windows 10
 - Provided sample code: No
 - Provided link: No