react-d3-tree
react-d3-tree copied to clipboard
Tree not in the middle of the container
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:
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
here is an example from the documentation on how to do this: https://codesandbox.io/s/vvz51w5n63
does this work with React Hooks? i cant convert the code given with the sandbox and not get an error in Chrome debugger
Me too
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>
)
}