简体   繁体   中英

how to handle multiple refs inside a map function

I need to target all the components inside map function, but I am only getting the last component inside it.

products?.map((product, i) => (
            <div
              key={product.id}
              className="product__card"
              onMouseEnter={() => sliderRef.current.slickNext()}
              onMouseLeave={() => sliderRef.current.slickPause()}
            >
              <StyledSlider {...settings} ref={sliderRef}>
                {product.assets.map(({ url, id, filename }) => (
                  <div className="product__image__container" key={id}>
                    <img src={url} alt={filename} />
                  </div>
                ))}
              </StyledSlider>
              <div className="product__content__container">
                <h3 className="slim__heading">{valueChopper(product.name, 23)}</h3>
                <p contentEditable="true" dangerouslySetInnerHTML={{ __html: valueChopper(product.description, 30) }} />
                <h6 className="slim__heading">Rs. {product.price.formatted}</h6>
              </div>
            </div>
          )

The simplest way is to use one ref to target multiple elements. See the example below. I've modified your code to make it work.

const sliderRef = useRef([]);

products?.map((product, i) => (
  <div
    key={product.id}
    className="product__card"
    onMouseEnter={() => sliderRef.current[i].slickNext()}
    onMouseLeave={() => sliderRef.current[i].slickPause()}
  >
    <StyledSlider {...settings} ref={el => sliderRef.current[i] = el}>
      {product.assets.map(({ url, id, filename }) => (
        <div className="product__image__container" key={id}>
          <img src={url} alt={filename} />
        </div>
    ))}
    </StyledSlider>
    <div className="product__content__container">
      <h3 className="slim__heading">{valueChopper(product.name, 23)}</h3>
      <p contentEditable="true" dangerouslySetInnerHTML={{ __html:valueChopper(product.description, 30) }} />
      <h6 className="slim__heading">Rs. {product.price.formatted}</h6>
    </div>
  </div>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM