4

I tried using a custom component with react-grid-layout. However, I could not get it working. When I put the component inside a div, I can resize that div, but the component itself is not resized with it. When I put the component inside the grid tags directly, I can't resize or move it at all and the borders of the grid are not matching the borders of the component either.

Here's the code for my index.js:

function App() {
return (
<div className="App" style={{ background: "grey" }}>
  <GridLayout className="layout" cols={16} rowHeight={10} width={500}>
    <div key="a" data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
      <TestComponent
        style={{
          color: "green",
          height: "auto",
          width: "auto",
          background: "red"
        }}
      />
    </div>

    <div
      key="b"
      data-grid={{ x: 5, y: 0, w: 3, h: 3 }}
      style={{ background: "green" }}
    >
      this works fine
    </div>

    <TestComponent
      key="c"
      data-grid={{ x: 1, y: 0, w: 2, h: 2 }}
      style={{
        color: "blue",
        height: "auto",
        width: "auto",
        background: "black"
      }}
    />
  </GridLayout>
</div>
);
}

I have uploaded the full example, including the TestComponent, on code sandbox: https://codesandbox.io/s/7zl7mm90m0

How can I implement a custom component properly on the grid?

Best regards,

W.

CWSites
  • 1,428
  • 1
  • 19
  • 34
GiaglS
  • 63
  • 1
  • 1
  • 5

1 Answers1

4

According to my expertise on react-grid-layout, you have to use a div to set data-grid property and inside that div you can pass your custom component. Otherwise, it will not work. This will work:

<div key="a" data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
  <TestComponent
    style={{
      color: "green",
      height: "auto",
      width: "auto",
      background: "red"
    }}
  />
</div>

else you can create a function for n-component and pass that function to grid like:

class App {
    renderElement(element) {
      return <div key={element} data-grid={{ x: 0, y: 0, w: 5, h: 10 }}>
          <TestComponent element={element} />
        </div>
    }
    render(){
    return (
    <div className="App" style={{ background: "grey" }}>
      <GridLayout className="layout" cols={16} rowHeight={10} width={500}>
        {[1,2,3,4,5].map(element=>this.renderElement(element))}
      </GridLayout>
    </div>
    );
     }
}