Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading Json response to a dropdown in react native

I'm using a material dropdown in my application

<Dropdown 
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
/>

I fetch JSON object like this and it works fine.

  fetch('url', {  
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      username : "admin"
    })
  }).then((response) => response.json())
  .then((responseJson) => {
    var count = Object.keys(responseJson.message.Obj).length;
    for(var i=0;i<count;i++){
      console.log(responseJson.message.Obj[i].name) // I need to add 
      //these names to dropdown
    }
  })
  .catch((error) => {
    console.error(error);
  });

Now I need to add the responseJson.message.Obj[i].name values to my dropdown list.

like image 241
unknown123 Avatar asked May 05 '26 20:05

unknown123


2 Answers

Supposing that you're using react-native-material-dropdown.

Example:

Dropdown component should be rendered as follows:

<Dropdown
  baseColor='white'
  itemColor='white'
  label='Select Cluster'
  data={this.state.drop_down_data} // initialise it to []
/>

Request code:

fetch('url', {
  ...
}).then((response) => response.json())
.then((responseJson) => {
  var count = Object.keys(responseJson.message.Obj).length;
  let drop_down_data = [];
  for(var i=0;i<count;i++){
    console.log(responseJson.message.Obj[i].name) // I need to add 
    drop_down_data.push({ value: responseJson.message.Obj[i].name }); // Create your array of data
  }
  this.setState({ drop_down_data }); // Set the new state
})
.catch((error) => {
  console.error(error);
});

Doc:

  • React native state management

  • react-native-material-dropdown

like image 166
Théo dvn Avatar answered May 07 '26 15:05

Théo dvn


You can achieve this by using react native "state". Create a state then assign it to Dropdown component's data property. Then set responseJson.message.Obj[i].names to the state by using "this.setState()" method.

like image 38
erkan Avatar answered May 07 '26 14:05

erkan