Search code examples
react-natived3.jsreact-native-svg

Treemap shape in React Native is not perfect (d3, react-native-svg)


I want to display treemap in react native and I found this blog. I tried to implement it in react native, it works but the shape is not perfect. I also tried to do in react, it works and the shape is perfect too. Sample

Can anyone let me know what I missed out in react native?

Treemap in react native

React native code:

import React from 'react'
import { Dimensions } from 'react-native'
import * as d3 from 'd3'
import * as SvgC from 'react-native-svg'
import { SafeAreaView } from 'react-native-safe-area-context'
const { Rect, G, Svg } = SvgC

interface Props {
  data: any
}

const TreeMap = ({ data }: Props) => {
  const windowWidth = Dimensions.get('window').width
  const windowHeight = Dimensions.get('window').height

  const root = d3
    .hierarchy(data)
    .sum((d) => d.value)
    .sort((a, b) => b.value - a.value)
  const treemapRoot = d3
    .treemap()
    .size([windowWidth, windowHeight])
    .padding(1)(root)

  const fader = (color) => d3.interpolateRgb(color, '#fff')(0.3)
  const colorScale = d3.scaleOrdinal(
    d3.schemeCategory10.map(fader)
  )
  return (
    <SafeAreaView>
      <Svg
        height={windowHeight}
        width={windowWidth}
        viewBox={`0 0 ${windowWidth} ${windowHeight}`}
      >
        {treemapRoot.leaves().map((leave) => {
          return (
            <G
              transform={`translate(${leave.x0},${leave.y0}`}
              onPress={() => console.log('hello')}
            >
              <Rect
                width={leave.x1 - leave.x0}
                height={leave.y1 - leave.y0}
                fill={colorScale(leave.data.category)}
              />
            </G>
          )
        })}
      </Svg>
    </SafeAreaView>
  )
}

export default TreeMap

Solution

  • Missed out the rect x and y position.

                  <Rect
                    x={leave.x0}
                    y={leave.y0}
                    width={leave.x1 - leave.x0}
                    height={leave.y1 - leave.y0}
                    fill={colorScale(leave.data.category)}
                  />
    

    enter image description here