Home > Enterprise >  Styling only to last index of an Array in typescript React?
Styling only to last index of an Array in typescript React?

Time:10-30

The only idea I have now is

if (customFields.values[0]) {
    <View style={styles.borderContainer} />; } 

For this array

let customFields: Array<{
              value: any;
              label: string;
            }> = [];

  if (query.data) {
              customFields = query.data.current_squad.custom_fields
                .filter(
                  (customField) =>
                    customField.is_visible_on_squads &&
                    customField.custom_field_value.value
                )
                .map((customField) => {
                  return {
                    value: customField.custom_field_value.value,
                    label: customField.title,
                  };
                });
              }
            }

But that doesn't work obviously. The end goal is to make a border at the last place in the array which is based on however many custom fields one makes. I am new to frontend and JS languages so any pointer to the right direction would be greatly appreciated.

CodePudding user response:

map higher-order function takes an index parameter, but you need to get your list length after filter function and before map function:

const exampleResult = custom_fields
  .filter(
    (customField) =>
      customField.is_visible_on_squads &&
      customField.custom_field_value.value
    )
)

const listLenght = exampleResult?.legnth;

const result = exampleResult
  .map(
    (customFiled, index) => {
      if(index === listLength -1 ) {
         return {
           value: customField.custom_field_value.value,
           label: customField.title,
           style: {styles.borderContainer}
         };
      } else {
         return {
           value: customField.custom_field_value.value,
           label: customField.title,
         };
      }
    }
  )

As another solution, you can add the style property to the last item after filter and map method:

const customFields = someData.filter(() => {}).map(() => {}) // just pseoudo

const lastItem = customFields[-1];

customFileds[-1] = {...lastItem, style: {styles.borderContainer}}
  • Related