4

I am using React-Flow in order to visualise a tree hierarchy of components in React. And whenever you create a custom node in React-Flow, you use it in the tree like that:

  <ReactFlow
      onLoad={onLoadTree}
      elements={nodesAndEdges}
      nodeTypes={{ reactComponent: ComponentNode }}

Which makes it impossible to pass props. Let's say that I want to pass something, then I would be able to do that if the syntax was like reactComponent: <ComponentNode myProps={myProps} />. Has anyone worked with this technology before and knows if it's somehow possible to pass props to a custom node? :) Thanks!

4 Answers 4

8

You can do like this

const YourComponent = () => {
  const componentNode = { reactComponent: (props) => <ComponentNode myProp="myProps" {...props} />};

  return (
    <ReactFlow
      onLoad={onLoadTree}
      elements={nodesAndEdges}
      nodeTypes={componentNode}
    />
  );
};

Here through props you get the predefined props like data, id etc.

0
4

You can pass any data you want in the data property section when creating a new node :

const newNode = {
  ...nodeProps,
  data: {
    myCustomProps: "test",
  },
}
0
1

It seems you can pass props in data property of node.

1

Hello from December 2022:

withProps HOC:

import { createElement } from 'react';

const withProps = (WrappedComponent, additionalProps = {}) => {
    return (props) => {
        return createElement(WrappedComponent, {
            ...props,
            ...additionalProps,
        });
    };
};

export default withProps;

Component:

const myNodeTypes= React.useMemo(
    () => ({
        myNode: withProps(myNode, { myProp }),
    }), [] 
);


<ReactFlow
    nodeTypes={myNodeTypes}
>
</ReactFlow>

Not the answer you're looking for? Browse other questions tagged or ask your own question.