SectionList data variable change to something like items in react native

73 Views Asked by At

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'], }, ];

2

There are 2 best solutions below

0
Adnan Ashraf On BEST ANSWER

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}
/>


0
Vicky Ahuja On

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
}, [])