0

I am trying to populate a semantic-ui-react drop-down with the first value(from the options parameter). But I am unable to do the same . Values for this dropdown I am fetching it from backend and then mapping it to a format supported by semantic-ui-react select.

Help would be appreciated.

  //state object
   this.state = {
                  users: [] ,
                  selectedUser: '',
                  defaultUser: string
   }
  //fetch call to get the values and then transforming 
  async componentDidMount()
  {
      try {       
             let data = await fetch('/api/fetch/users')
             let users =  await data.json();
             users = users.map((obj:any) => ({            //formatting the list to support options array of semnatic-ui-react select
                                              key: obj.id,
                                              text: obj.name,
                                              value: obj.name
                                        }));
             this.setState({users},defaultUser: users[0].value); //setting the dropdown with first value, but it is not happening

     }
     catch(e){
         console.log('Error', e.message);
     }
  } 


   //onchange handler
   dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
     this.setState(prevState => ({
                [data.name]: data.value
     }));
    }

  //Inside render, Select

   <Select 
                             options={this.state.users} 
                             name="selectedUser"  
                             value={this.state.selectedUser}
                             onChange={this.dropdownChange}  
                             defaultValue = {this.state.defaultUser}  
   />
0

1 Answer 1

1

I think you don't need the defaultValue prop. You can check out the codesandbox bellow. I used react hooks but you get the point.

https://codesandbox.io/s/heuristic-wiles-eq7su

For your particular code:

import React from "react";
import ReactDOM from "react-dom";
import { Select } from "semantic-ui-react";


class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
      selectedUser: ""
    };
  }
 async componentDidMount(){
  try {       
         let data = await fetch('/api/fetch/users')
         let users =  await data.json();
         users = users.map((obj:any) => ({
                                          key: obj.id,
                                          text: obj.name,
                                          value: obj.name
                                    }));

         this.setState({users}, () => {
            this.setState({selectedUser: this.state.users[0].value});
         })

 }

  //onchange handler
  dropdownChange = (event, data) => {
    this.setState({ selectedUser: data.value });
  };

  render() {
    return (
        <Select
          onChange={this.dropdownChange}
          placeholder="Select a user"
          value={this.state.selectedUser}
          selection
          options={this.state.users}
        />
    );
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the reply. It is using a latest react version . Something that is similar to my snippet in the question would be really great!
You can check now. I updated the code to use lifecycle methods and this.state.
It is giving the following error " Argument of type '(state: any) => void' is not assignable to parameter of type '() => void' " . I am using typescript with react
I updated the answer for your particular code. Can you try it and see if it works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.