0

I'm making a custom Tree using Ant Design.

I have a treeData with color property, I made an array of treeNode ref by binding ref of that treeNode into treeNodeRef

<TreeNode ref={(ref) => (treeNodeRef.current[key] = ref)}>

then iterate treeNodeRef to change style of that treeNode like this:

  useEffect(() => {
    treeNodeRef.current.forEach((element, index) => {
      element.style.backgroundColor = treeRef.state.treeData[index].color;
      console.log(element);
    });
  }, [treeNodeRef, treeRef]);

But my treeNode.current always empty, what is wrong?

Can I change treeNode in this way?

Each TreeNode component has a checkbox, so how can change the style of that checkbox?

This is my code: https://codesandbox.io/s/controlled-tree-antd4100-forked-e29pk

dungreact
  • 442
  • 1
  • 9
  • 22
  • Your assumption is that there is a `element.style.backgroundColor` property. But `TreeNode` is a custom component, you need to check what props does `element` has as you can't know the inner implementation (or just check `antd` github) – Dennis Vash Jan 09 '21 at 12:35
  • 1
    As a side note, antd is a **Design System**, meaning you don't suppose to change it styles – Dennis Vash Jan 09 '21 at 12:36
  • I just thinking about this way, do you have any suggestions? I have to custom it :3 – dungreact Jan 09 '21 at 12:39
  • 1
    You can "hack" the css by checking it styles via CSS and overriding it. But the problem is in "I HAVE to custom it", that's more of a design error, you probably should have picked more modular components that allow styling - in antd it's pretty hard and not maintainable. – Dennis Vash Jan 09 '21 at 12:41
  • @DennisVash do you know any lib can do that? – dungreact Jan 09 '21 at 13:00

2 Answers2

0

I solved my problem by not using useRef. I wrap the Tree with a Checbox Group then disable checkable on Tree, render a custom title with a styled checkbox.

dungreact
  • 442
  • 1
  • 9
  • 22
-1

This is the approach used in class based components

<TreeNode ref={(ref) => (treeNodeRef.current[key] = ref)}>

In functional component, you have do like this

import React, { useState } from "react";

const MyComponent = (props) => {
  const [selected, setSelected] = useState([]);

  useEffect(() => {
    selected.forEach((element, index) => {
      element.style.backgroundColor = treeRef.state.treeData[index].color;
      console.log(element);
    });
  }, [selected]);

  return <Tree onSelect={selected} selectedKeys={setSelected} />;
};