reactjsrefs

How to get a ref array


Hello guys !

export default class Test extends React.Component {
    constructor(props) {
        super(props);
        this.ref = [];
    }

    handleClick = () => {
        let doc;
        doc = this.refs["link" + 0];
        console.log("ref is => " + doc.innerHTML);
    }

    render() {
        return (
            <div>
                <p ref={"link" + 0} onClick={this.handleClick}> p1</p>
                <p ref={"link" + 1} onClick={this.handleClick}> p2</p>
            </div>
        );
    }
}

How can I know on which link i clicked when I enter in the function handleClick ? Thanks for help !


Solution

  •   export default class Test extends React.Component {
    
        handleClick = (linkRef) => {
            console.log("ref is => " + this.refs[linkRef].innerHTML);
        }
    
        render() {
            return (
                <div>
                    <p ref='linkOne' onClick={() => this.handleClick('linkOne')}> p1</p>
                    <p ref='linkTwo' onClick={() => this.handleClick('linkTwo')}> p2</p>
                </div>
            );
        }
    }