react-d3-tree icon indicating copy to clipboard operation
react-d3-tree copied to clipboard

Tree not in the middle of the container

Open peterbe opened this issue 4 years ago • 4 comments

Are you reporting a bug, or opening a feature request?

Not sure. It could just be a user error. Either way, it's not clear how to resolve it.

What is the actual behavior/output?

See https://codesandbox.io/s/pensive-liskov-1mtcs?fontsize=14&hidenavigation=1&theme=dark If it doesn't load, it looks like this: Screen Shot 2020-02-10 at 11 01 00 AM

I started a fresh create-react-app project and the same thing happened there too. I'm not a CSS wiz but I thought I should be able to figure it out but I couldn't. The exact same problem appears with the Codesandbox.

What is the behavior/output you expect?

I would expect the root node to figure out, automatically, what the center is of the container and start there.

Can you consistently reproduce the issue/create a reproduction case (e.g. on https://codesandbox.io)?

See codesandbox

What version of react-d3-tree are you using?

See codesandbox

peterbe avatar Feb 10 '20 16:02 peterbe

here is an example from the documentation on how to do this: https://codesandbox.io/s/vvz51w5n63

julientregoat avatar Feb 10 '20 17:02 julientregoat

does this work with React Hooks? i cant convert the code given with the sandbox and not get an error in Chrome debugger

confrodog avatar Jun 25 '20 15:06 confrodog

Me too

lzq127001 avatar Jul 31 '20 08:07 lzq127001

For everyone else out there trying to figure out how to center the tree while using function components, I found a solution.

It's not perfect (in particular, I don't like the shouldRecenterTreeRef part, but for some reason the [] dependency in useEffect is not enough), but it works.

const CenteredTree = () => {
  const shouldRecenterTreeRef = useRef(true);
  const [treeTranslate, setTreeTranslate] = useState({ x: 0, y: 0 });
  const treeContainerRef = useRef(null);

  useEffect(() => {
    if (treeContainerRef.current && shouldRecenterTreeRef.current) {
      shouldRecenterTreeRef.current = false;
      const dimensions = treeContainerRef.current.getBoundingClientRect();

      setTreeTranslate({
        x: dimensions.width / 2,
        y: dimensions.height / 2,
      });
    }
  });

  return (
    <div ref={treeContainerRef} style={{ height: '100vh' }}>
      <D3Tree
        data={yourData}
        collapsible={false}
        pathFunc="step"
        translate={treeTranslate}
        orientation="vertical"
      />
    </div>
  )
}

amberv0 avatar Feb 13 '21 12:02 amberv0