Search code examples
reactjselementchildrenclone-element

Using React.clone element vs not using it for applying a prop


i saw a code snippet which write this:

<OmniCarousel settings={sliderSettings}>
        {React.Children.map(children, (child, index) => <div key={`dashboardBanner_${index}`}>{child}</div>)}
      </OmniCarousel>

but i was wondering why it was not written as:

<OmniCarousel settings={sliderSettings}>
            {React.Children.map(children, (child, index) => React.cloneElement(child,<div key={`dashboardBanner_${index}`}>{child}</div>)}

The code compiles fine both ways. Is there someone to answer this?


Solution

  • They both are almost the same, with only difference in references. If you want to pass ref to child you can use React.cloneElement.

    Docs: https://reactjs.org/docs/react-api.html#cloneelement