0

I want to display all months in dropdown using react js. Below is my code .I have used moments to fetch all 12 months. I am getting value in console but not in my dropdown.

To display the dropdown values want to use the . I have used that also. I don't know where I went wrong. Could any one can help me with this? Thanks in advance.

const fareMon = () => {
      const months = [];
      const monthList = moment.months();
      months.push(<option value={monthList} />);
      console.log('MONTHS123', monthList);
      return months;
};
return (
<div className={styles.formClm2}>
    <Form.Group className={styles.formGroup}>
        <Form.Label>{t('PaymentPage.lblExpiry')}</Form.Label>
        <div className="double">
            <Form.Control required as="select" name="startDate">
                <option value="">Months</option>
                {fareMon()}
            </Form.Control>
        </div>
    </Form.Group>
</div> )

3 Answers 3

1
const fareMon = () => {
  const monthList = moment.months();
  const months = monthList.map(item => (
    <option key={item} value={item}>{item}</option> 
  ));
  console.log('MONTHS123', monthList);
  return months;
};

you need to iterate the monthsList and map each month to a <option>.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to iterate over the array of months and set the value in the form controls options element.

Something like this, something simplified.

<Form.Control required as="select" name="startDate">
  {months.map(month => (<option key={month.id} value={month.value}>{month.label}</option>))}
</Form.Control>

Key points:

  • Iterate over a data source of some description.

  • Ensure each option has a key prop

Comments

1

moment.months() returns an array containing the months name, you don't need to create a new array.

You have to map over the array inside the Select to show up the options.

Example:

const fareMon = () => {
    const monthList = moment.months();
    return monthList;
};
return (
    <div className={styles.formClm2}>
        <Form.Group className={styles.formGroup}>
            <Form.Label>{t('PaymentPage.lblExpiry')}</Form.Label>
            <div className="double">
                <Form.Control required as="select" name="startDate">
                    <option value="">Months</option>
                    {fareMon().map( month => (<option key={month} value={month}>{month}</option>))}
                </Form.Control>
            </div>
        </Form.Group>
    </div>
)

Comments

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.