How to create a dynamic dropdown with info fetched from mysql in react js

This is my code in my index,jsx file for fetching the info of all students from database

import React, { Component } from 'react'

import * as myConstClass from '../../../constant.js'
class Students extends Component {
  constructor(props) {
    super(props)
    this.state = {
      students: [],
    }
  }
  componentDidMount() {
    fetch(myConstClass.BASE_URL + 'students//get_all_students/')
      .then(response => response.json())
      .then(response => {
        this.setState({ students: response })
      })
      .catch(err => console.log(err))
  }

  render() {
    const { students } = this.state
    return (
      <div>
        <Field
          name="student_id"
          component={renderTextField}
          select
          label="Select student"
        >
          <MenuItem className="material-form__option" value={students.id}>
            {students.first_name}
          </MenuItem>
        </Field>
      </div>
    )
  }
}

but the dropdown is not populating , how can I do it ?

Hi @xcfx2888, according to your initial state students is supposed to be an array, but inside your render() method you’re treating it like a single student item; so you’ll probably have to render the data as a list:

(Also, where is Field and renderTextField defined?)

1 Like

Try this coding:

<Field
  name="student_id"
  component={renderTextField}
  select
  label="Select student"
>
  {students.l > 0 &&
    students.map((i, k) => {
      return (
        <MenuItem key={k} className="material-form__option" value={i.id}>
          {i.first_name}
        </MenuItem>
      )
    })}
</Field>

This coding may help you.

1 Like

@qservicesinc posted how you should do it and it’s mostly correct. However, you should avoid using an index as a key in React. Keys are very important and should be unique to the element rendered.

It’s explained here:

A better key in this case would be:

key={`studentmenu-${item.id}`}
1 Like

I tried this exactly same but still the drop down is showing blank

Can you send me your data example?

1 Like