Home > database >  I need to create a dropdown in antdesign and set state
I need to create a dropdown in antdesign and set state

Time:11-19

I am building a reusable component that returns an Ant Design Select dropdown menu. I am struggling to take the value, and set it to state in the parent component.

Below is the dropdown generator.

import React from 'react';
import { Select } from 'antd';

const { Option } = Select;

// This function will generate a dropdown menu that will render from a list of options to be            mapped. It also requires a changeHandle function to be passed in as a prop, likely to be used to set               the state of the parent component.

const DynamicDropdown = ({ options, name, onChange, data, setaData }) => {
//options is an array of options to be mapped
//name is the name of the dropdown menu
//data is the state of the parent component
//setaData is the function to set the state of the parent component

return (
<Select
  showSearch
  name={name}
  style={{ width: 200 }}
  placeholder="Select a person"
  optionFilterProp="children"
  filterOption={(input, option) =>
    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }
  name={name}
>
  {options.map(option => (
    <Option value={option} onChange={onChange} name={name}>
      {option}
    </Option>
  ))}
</Select>
);
};

export default DynamicDropdown;

data and setData being sent in props is the state below.

const [formData, setFormData] = useState({
meeting_topic: '',
meeting_start_time: '',
meeting_end_time: '',
mentor_id: '',
mentee_id: '',
admin_meeting_notes: '',
mentor_meeting_notes: '',
mentee_meeting_notes: '',
});

The data options prop is the following.

const mentees = ['Mentee 1', 'Mentee 2', 'Mentee 3'];

The onChange prop is the following functionn

const handleChange = e => {
setFormData({ ...formData, [e.target.name]: e.target.value });
console.log(formData);
};

Any idea what I might be doing wrong>? I have tried multiple combos of different things in different places. I can't seem to find much documentation on setting Select into state. Thank you!

Have tried moving changeHandel directly into the component, moved the name around to different spots including in the returnedJSX. I even broke reusability by setting state directly in the dynamicDropdown itself.

CodePudding user response:

your data structure for optins is not valid. the optoins array shoul be like this:

const options=[
        {
          value: 'jack',
          label: 'Jack',
        },
        {
          value: 'lucy',
          label: 'Lucy',
        },
        {
          value: 'disabled',
          disabled: true,
          label: 'Disabled',
        },
        {
          value: 'Yiminghe',
          label: 'yiminghe',
        },
      ]

each element should have value and label to see complete code click here: complete code

  • Related