Reactjs how to use ref inside map function?

sir-haver picture sir-haver · Jan 22, 2019 · Viewed 15.2k times · Source

I'm mapping through an array and for each item display a button with text. Say I want that on clicking the button, the text underneath will change its color to red. How can I target the sibling of the button? I tried using ref but since it's a mapped jsx, only the last ref element will be declared.

Here is my code:

class Exams extends React.Component {
    constructor(props) {
        super()
        this.accordionContent = null;
    }
    state = {
        examsNames: null, // fetched from a server
    }
    accordionToggle = () => {
        this.accordionContent.style.color = 'red'
    }
    render() {
        return (
            <div className="container">
                {this.state.examsNames && this.state.examsNames.map((inst, key) => (
                    <React.Fragment key={key}>
                        <button onClick={this.accordionToggle} className="inst-link"></button>
                        <div ref={accordionContent => this.accordionContent = accordionContent} className="accordionContent">
                            <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aperiam, neque.</p>
                        </div>    
                    </React.Fragment>
                ))}
            </div>
        )
    }
}


export default Exams;

As explained, the outcome is that on each button click, the paragraph attached to the last button will be targeted.

Thanks in advance

Answer

Prakash Sharma picture Prakash Sharma · Jan 22, 2019

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