How to pass a reference to the child component in a compound component?

37 Views Asked by At

I have a compound component like this, and I want to pass a reference that reaches the CardContent:

const Product = ({ products }) => {
    const ref = useRef();
    return (
        products[0].map(product => (
            < Card
                key={product.id}
                ref={ref}
                className="Card"
                CardData={product}
                content={{ content1: product.sizes, content2: product.price, content3: product.inStock }}
            >
                <CardImage className="Card_IMG" />
                <CardTitle />
                <CardContent className="Card_Content" />
                <CardBotton />
            </Card >
        ))

        /*  products[0].map(product =>
             (<h3 key={product._id}>{product.title}</h3>)) */
    )
}

export default Product;
```js

The ref of the parent component comes from a `useRef()`. The Card component that is going to pass properties to its children, which are `CardImage`, `CarTitle`, `CardContent`, `CardBotton` is going to use the `CloneElement` to send props to its children.

```js
import { Children, cloneElement, forwardRef, useRef } from "react";

const Card = forwardRef(({ CardData, content, className, style, key, children }, ref) => {

  return (
    <div key={key} className={className} style={style} >
      {Children.map(children, (child) =>
        cloneElement(child, {
          CardData,
          content,
          ref: ref
        })
      )}
    </div>
  )
})

export default Card;

A very strange thing that happens to me is that if I make a ref console.log, the reference to the div appears

**current**: div.Card [Prototype]: Object

but if I do console.log of ref.current, it says it is undefined. I don't understand.

export const CardContent = ({ description, className, style, product, content, ref }) => {

  return (
    <div className={className} ref={ref} >
      <div>
        <h3>{(content1) ? content1 : cardData.content1}</h3>
      </div>

      {(content2 && content3) ? '' : (
        <div >
          <h3>{(content2) ? content2 : cardData.content2}</h3>
          <h3>{(content3) ? content3 : cardData.content3}</h3>
        </div>
      )}

    </div>
  )
}

I want to know how to iterate with the ref and pass the reference to the children.

0

There are 0 best solutions below