Home > Enterprise >  Calling function defined within a react function component on a click event form another function co
Calling function defined within a react function component on a click event form another function co

Time:07-07

I am constructing some node objects in a function(prepareNodes) to pass to React Flow within a functional component A (lets say), and I have defined a custom node component(CardNode) stateless, which has a button. On button click it should trigger the function(prepareNodes) defined within Component A.

    function ComponentA = ({ selectedNodes }) => {
    
         const reactFlowWrapper = useRef(null);
    
         const [elements, setElements] = useState([]);
         const [edges, setEdges] = useState([]);
   
         const prepareNode = async (nodeid) => {
            //some service calls to fetch data and constuct nodes
            setElements([ ...nodes]);
            setEdges([...edges]);
         }

       return (
        <ReactFlowProvider>
          <div className="reactflow-wrapper" ref={reactFlowWrapper}>
            <ReactFlow
              nodes={elements}
              edges={edges}
              //some properties
            >
            </ReactFlow>
          </div>
        </ReactFlowProvider>
       )
   };
   export default ComponentA;


   function CardNode({ data }) {
  
    const renderSubFlowNodes = (id) => {
      console.log(id);
      //prepareNode(id)
    }
  
    return (
        <>
          <Handle type="target" position={Position.Top} />
          <div className="flex node-wrapper">
              <button className="btn-transparent btn-toggle-node" href="#" onClick={() => renderSubFlowNodes(data['id']) }>
                  <div> 
                      <img src={Icon}/>    
                  </div>
              </button>
          </div>
          <Handle type="source" position={Position.Bottom}/>
       </>
    );
  }
  
  export default CardNode;

I looked for some references online, and most of them suggest to move this resuable function out of the component, but since this function carries a state that it directly sets to the ReactFlow using useState hook, I dont think it would be much of a help.

Other references talks about using useCallback or useRefs and forwardRef, useImperativeHandle especially for functional component, Which I did not quite understand well.

Can someone suggest me a solution or a work around for this specific use-case of mine.

CodePudding user response:

You can add an onClick handler to the each node, and within the node view you call this handler on click.

In the parent Component within the onClick handler you can call prepareNode as needed.

useEffect(() => {
setElements(
  elements.map(item => {
    ...item,
    onClick: (i) => {
      console.log(i);
      prepareNode();
    },
  })
)}, 
[]);

CodePudding user response:

The classical approach is to have a parent object that defines prepareNode (along with the state items it uses) and pass the required pieces as props into the components that use them.

That "parent object" could be a common-ancestor component, or a Context (if the chain from the parent to the children makes it cumbersome to pass the props all the way down it).

  • Related