reactjsreact-grid-layout

React-grid-layout not updating properly with new elements unless I force its resizing


I have the following layout in my state

layouts: {
            //x = starting from 0 horizontal position
            //y = starting from 0 vertical position
            //h = height of the el
            //minW = position relative to x width, from x(pos1) to x(pos2)
            lg: [
                { i: 'a', x: 0, y: 0, w: 6, h: 6.45 },
                // {i: 'b', x:6, y:0, w:6, h:6.45}
            ],
            md: [
                { i: 'a', x: 0, y: 0, w: 5, h: 4.35 }
                // {i: 'b', x:6, y:0, w:5, h:4.35}
            ],
            sm: [
                { i: 'a', x: 0, y: 0, w: 1, h: 2 },

            ],
            xs: [
                { i: 'a', x: 0, y: 0, w: 1, h: 2 },

            ],
            xxs: [
                { i: 'a', x: 0, y: 0, w: 1, h: 2 },

            ]
        }

Loaded into this responsivegridlayout component

<ResponsiveGridLayout className="layout"
                        layouts={this.state.layouts}
                        margin={[0, 0]}
                        breakpoints={{ lg: 1300, md: 1000, sm: 768, xs: 480, xxs: 0 }}
                        cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}>
                        {_.map(this.state.layouts.lg, el => this.createElement(el))}
                    </ResponsiveGridLayout >

it works fine but whenever I want to add a new element to the layout in this function

closeAddModal = (el) => {
    console.log(el.target.getAttribute('name'))
    this.setState({
        addAppModal: false
    })

    var layouts = this.state.layouts;

    layouts.lg.push({ i: 'b', x: 6, y: 0, w: 6, h: 6.45 })
    // layouts.md.push({i: 'b', x:6, y:0, w:5, h:4.35})

    this.setState({
        layouts: layouts
    }, () => {
        console.log(this.state.layouts)


    }
    )
}

Where I push the element into the state of the layout, it gets added in an unproper position and in the smallest possible size. And it will only align properly after I manually resize the browser.

Keep in mind that, if I render the added element initially, its rendered in the proper position


Solution

  • I kind of used this as a workaround, but its really messy, and I had to change a bit the structure of the app

    {this.state.addAppModal ? null : <ResponsiveGridLayout className="layout"
                            layouts={this.state.layouts}
                            margin={[0, 0]}
                            breakpoints={{ lg: 1300, md: 1000, sm: 768, xs: 480, xxs: 0 }}
                            cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}>
                            {_.map(this.state.layouts.lg, el => this.createElement(el))}
                        </ResponsiveGridLayout >}
    

    Basically what I did, is rerender the whole responsivegridlayout after its updated with a "null" , because apparently setstate doesnt update it properly