Reactjs How to Use Ref Inside Map Function

Reactjs how to use ref inside map function?

Initialize this.accordionContent as an array

constructor(props) {
super()
this.accordionContent =[];
}

And set the ref like this

<div ref={accordionContent => this.accordionContent[key] = accordionContent} className="accordionContent">

ReactJS .map with a ref to each component

Create an empty object to hold your refs.

const allTheRefs = {}

Then in each map iteration, write the ref to that object, with using the map key as the object key

{displayUnavail && !displaySearch && 
notAvailable.map((tracker) => (
<IndividualTracker ref={ref => allTheRefs[tracker.pim] = ref } ... />
)
}

Once your map statement is executed, your allTheRefs variable will contain all the refs as key value pairs, with the keys being the tracker.pim value, and the value being the ref itself.

Here is a working codesandbox

how to handle multiple refs inside a map function

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>
)

Using .map() to generate elements with Refs

Define a function for a ref and store the refs in the class variable object like

constructor(props) {
super(props);

this.state = {
people: {
tango: { height: 10, weight: 200 },
cash: { height: 20, weight: 300 }
}
};
this.domRefs = {};
}
outputStatePeople(key) {
return (
<span className="db" key={key} ref={(ref) => {this.domRefs[key] = ref}}>
name: {key}, height: {this.state.people[key].height}
</span>
);
}

You can read more about Refs and Dom Here

How can I assign a new ref to every iteration inside a map function?

I'd handle this by using CSS if at all possible, rather than handling hovering in my JavaScript code.

If doing it in JavaScript code, I'd handle this by creating a component for the things that are hovered:

function MyImage({src, header}) {
const [ref, hovered] = useHover();
return (
<div className="row imageSpace">
{hovered && <h1>{header}</h1>}
<img
ref={ref}
className="image"
alt="fall"
src={src}
/>
</div>
);
}

and then use that component:

return (
<Wrapper>
<Styles className="row">
<Div className="col-xs-4">
{data.map(item =>
<MyImage
key={item.sys.id}
src={item.fields.image.file.url}
header={item.fields.name}
/>
)}
</Div>

(Obviously, make more of the props configurable if you like.)

How can I add refs in map

You must have a function in ref which assigns the ref

function App() {
let numRef = useRef([]);

const mat = [1, 2, 3, 4, 5];

console.log(numRef); //
return (
<div className="App">
<div>
{mat.map((element, idx) => (
<p ref={(ref) => numRef.current[idx] = ref} type="text">
{element}
</p>
))}
</div>
</div>
);
}


Related Topics



Leave a reply



Submit