Adnan Ashraf
Adnan Ashraf

Reputation: 188

SectionList data variable change to something like items in react native

How can i change the scheme for data to something like items or agents in our array that we providing to sectionList. section list accepts array like this : const DATA = [ { title: 'Main dishes', data: ['Pizza', 'Burger', 'Risotto'], }, { title: 'Sides', data: ['French Fries', 'Onion Rings', 'Fried Shrimps'], }, { title: 'Drinks', data: ['Water', 'Coke', 'Beer'], }, { title: 'Desserts', data: ['Cheese Cake', 'Ice Cream'], }, ]; is it possible to change the data to agent const DATA = [ { title: 'Main dishes', agent: ['Pizza', 'Burger', 'Risotto'], }, { title: 'Sides', agent: ['French Fries', 'Onion Rings', 'Fried Shrimps'], }, { title: 'Drinks', agent: ['Water', 'Coke', 'Beer'], }, { title: 'Desserts', agent: ['Cheese Cake', 'Ice Cream'], }, ];

Upvotes: 0

Views: 169

Answers (2)

Adnan Ashraf
Adnan Ashraf

Reputation: 188

I solved this by passing the whole section to the function and then got the item from section based on the index

const DATA = [{
    title: 'Main dishes',
    agent: ['Pizza', 'Burger', 'Risotto'],
    data: ['Pizza', 'Burger', 'Risotto']
}, {
    title: 'Sides',
    agent: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
    data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
}, { title: 'Drinks', agent: ['Water', 'Coke', 'Beer'], }, {
    title: 'Desserts',
    agent: ['Cheese Cake', 'Ice Cream'],
    data: ['Cheese Cake', 'Ice Cream'],
},];

const renderItem=({ section, item, index })=>{
return <RenderItemComponent data={section.agent[index]} key={index} />
}

<SectionList
  sections={DATA}
  renderItem={renderItem} 
  renderSectionHeader={renderSectionHeader}
/>


Upvotes: 0

Vicky Ahuja
Vicky Ahuja

Reputation: 1214

I don't think its possible, As section list uses Flatlist component props in array of sections.

See Section Data Prop Document

One thing you can do is to use the reduce function to change the agent key in your response to data key.

eg.

DATA.reduce((prevVal, currVal) => {
    const arr = [...prevVal]
    const objData = [...currVal.agent]
    delete currVal.agent
    const res = [...arr, {
        ...currVal,
        data: objData
    }]
    return res
}, [])

Upvotes: 0

Related Questions