Search code examples
javascriptreactjsreact-grid-layout

React is not rendering after the deletion of an object in array


I am a beginner and I am having hard time about figuring this out. I have delete button with my each item in a list. When I hit the button, the object in the firstItems array is being deleted (I can see it when I log the array to the console), but my list is not being rendered. Here is my code below :

import Sample from './SampleBlock'
import React from 'react'
import { useState } from 'react'
import { Responsive, WidthProvider } from 'react-grid-layout'
const ResponsiveGridLayout = WidthProvider(Responsive)

const firstItems = [
    { i: '1', comp: Sample },
    { i: '2', comp: Sample },
    { i: '3', comp: Sample },
    { i: '4', comp: Sample },
    { i: '5', comp: Sample },
]

const firstLayout = {
    lg: [
        { i: '1', x: 0, y: 0, w: 1, h: 2 },
        { i: '2', x: 1, y: 0, w: 3, h: 2 },
        { i: '3', x: 4, y: 0, w: 1, h: 2 },
        { i: '4', x: 0, y: 2, w: 2, h: 2 },
        { i: '5', x: 0, y: 2, w: 6, h: 2 },
    ],
}

export default function Content() {
    const [layout, setLayout] = useState(firstLayout)
    const [items, setItems] = useState(firstItems)

    const edit = (_, allLayouts) => {
        console.log(allLayouts)
        setLayout(allLayouts)
    }

    const onRemoveItem = (itemId) => {
    setItems(items.filter((item) => item.i !== itemId))
    }

    return (
        <ResponsiveGridLayout className='layout' layouts={layout} onRemoveItem={onRemoveItem} onLayoutChange={edit} breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }} cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 1 }} rowHeight={60}>
            {firstItems.map((item) => (
                <div key={item.i} className='widget' data-grid={{ w: 3, h: 2, x: 0, y: Infinity }}>
                    <button onClick={() => {onRemoveItem(item.i)}}>{item.i}</button>
                      <div style={{ width: '100%', height: '100%', backgroundColor: '#ccc' }}>       {React.createElement(item.comp, { key: item.i })}</div>
                </div>
            ))}
        </ResponsiveGridLayout>
    )
}


Solution

  • You are looping through wrong elements, it should be

    items.map((item) => 
    

    instead of

    firstItems.map((item) =>