Is it possible to update the color of a custom node by ID in react-flow?

Viewed 500

As the documentation states I am passing the props needed for custom nodes and using the nodeId prop to change the color of my nodes on click. My current workflow changes the color of all the nodes instead of just the one I clicked.

How can I change the color of the custom Node that I click?

My current workflow is as follows.

const [customNodeStyles, setNodeStyles] = useState({
    background: 'black',
    padding: 10,
    borderRadius: 50,
    width: 10,
    height: 10
});

const onElementClick = (event, element) => {
    setNodeBg('red');
    setNodeId(element.id);
}

useEffect(() => {
    setNodeStyles({ ...customNodeStyles, background: nodeBg });

}, [nodeId, nodeBg]);

return (
    <div style={{ height: 1000, width: 1000 }}>
        <ReactFlow
            elements={elements}
            nodeTypes={{ special: CustomNodeComponent }}
            nodeTypesId={nodeId}
            onElementClick={onElementClick}
            defaultZoom={1.5}
            minZoom={0.2}
            maxZoom={4}>
        </ReactFlow>
    </div>
);
1 Answers

Passing in a nodeId into the nodeTypesId will re-render the styling for all the nodes.

What you need to do is to change the state of the backgroundColor on click. I suggest creating a React Element for your Circle Node (which will contain a div and a style element with all the necessary css fields) that gets an object and sets backgroundColor when rendered.

Related