Skip to content
Advertisement

how can you set a dynamic list in react?

I have a list like this

this.days = [
            { key: 0, text: '0 Day', value: 0 },
            { key: 1, text: '1 Day', value: 1 },
            { key: 2, text: '2 Days', value: 2 },
            { key: 3, text: '3 Days', value: 3 }
        ];

//I use the list as options for drop down

<Dropdown
    name="listOfDays"
    placeholder="Days"
    selection
    options={this.days}
    value={this.state.listOfDays}
    onChange={this.handleChange}
/>

My problem is, I want to set the maximum days of the list from a configuration so sort of like this

let CONFIG_MAX_SOMETHING = 5;
this.days = [
  for(let i = 0; i < CONFIG_MAX_SOMETHING; i++) {
    { key: i , text: i + 'Day', value: i }
  }
]

I know this seems an easy thing to implement but Im new to react and cannot seem to find a similar question. Thanks

Advertisement

Answer

A common way is to use Array.prototype.push to populate such an array:

let CONFIG_MAX_SOMETHING = 5;

this.days = [];
for(let i = 0; i < CONFIG_MAX_SOMETHING; i++) {
  this.days.push({ key: i , text: i + (i === 1 ? ' Day' : ' Days'), value: i })
}

console.log(this.days);

Or you could use array APIs such as Array.from to dynamically generate such an array directly.

let CONFIG_MAX_SOMETHING = 5;

this.days = Array.from({ length: 5 }, (_, i) => (
  { key: i , text: i + (i === 1 ? ' Day' : ' Days'), value: i }
));

console.log(this.days);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement