4

I have a component with state that gets updated as a result of some async operations. This component is part of some drag and drop UI, when a user begins a drag operation I need to render this component in a separate part of the application that's responsible for displaying the dragged element.

The problem is that if I render a component anew elsewhere, even if I pass the same props it will still have to run through the async operations before it can render the component from the same state as the drag source.

I thought I could make it work by doing something like this - render method of the component referencing the drag source:

render() {
    return (
        <DragSourceComponent ref={this.dragSourceComponentRef} />
    )
}

And a different component render method responsible for rendering the drag preview component:

renderDragPreview(dragSourceComponentRef) {
    return React.cloneElement(dragSourceComponentRef.current)
}

However this doesn't work because dragSourceComponentRef.current isn't considered a valid React element and even if it were, I don't think React.cloneElement copies a component's state (documentation isn't clear on this).

All of this in mind, what are some other options that I have? Is it possible to say, pre-set a component's state before it's rendered for the first time? If that were the case I might be able to render the drag preview component with the same props and a cloned state and have it look exactly the same as the drag source element. Any other ideas/advice appreciated!

styke
  • 2,116
  • 2
  • 23
  • 51
  • You just need the state to create a clone. You can use contextApi to share the state or redux. – Tan Nov 08 '18 at 12:36

1 Answers1

0

You just need to share a state with multiple similar components, not copy the siblings components state to the copied one. You have two options here:

  1. Move the DragSourceComponent' states to its parents components and get them via props;
  2. Move the DragSourceComponent' states to a context, and get them via React.useContext() hook anywhere you want to
Pedro Henrique
  • 181
  • 3
  • 11