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

Here is my working codepen example based on your code above

Linked example is an "actual" accordion, ie display and hide adjacent content.

(see code snippets below for turning to red)

https://codepen.io/PapaCodio/pen/XwxmvK?editors=0010


CODE SNIPPETS

initialize the referance array:

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

add the ref to the reference array using the key:

<div ref={ref => (this.accordionContent[key] = ref)} >

pass the key to the toggle function via onClick

 <button onClick={() => this.accordionToggle(key)} >

finally reference the key inside the toggle function

accordionToggle = key => {
    this.accordionContent[key].style.color = 'red'
};

Tags:

Css

Ref

Reactjs