Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs how to use ref inside map function?

Tags:

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

like image 331
sir-haver Avatar asked Jan 22 '19 19:01

sir-haver


People also ask

Can we use REF in functional component?

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.

How do you use REF in functional component?

To create a ref in a functional component we use the useRef() hook which returns a mutable object with a . current property set to the initialValue we passed to the hook. This returned object will persist for the full lifetime of the component. Thus, throughout all of its re-rendering and until it unmounts.

How do you pass a ref to a component?

We define a ref in the component that needs the ref and pass it to the button component. React will pass the ref through and forward it down to <input ref={ref}> by specifying it as a JSX attribute. When the ref is attached, ref. current will point to the <input> DOM node.


2 Answers

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">
like image 157
Prakash Sharma Avatar answered Oct 02 '22 22:10

Prakash Sharma


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'
};
like image 44
PapaCodio Avatar answered Oct 02 '22 20:10

PapaCodio