indarCode
indarCode

Reputation: 90

Get the value of clicked element in : React

How to get the value of a clicked element in react. event.currentTarget.value shows 'undefined' in react 16. Does anyone know what is the trick here ?? BTM here is the code for an instance:

class Test extends React.Component{
        constructor(){
            super();
    }

changeDimension(e){
    alert(e.currentTarget.value);
}

        render(){
            return(
            <div style={{height : this.state.height}} >
                        <h1 onClick={this.changeDimension.bind(this)}> Click Me</h1>
                    </div>
        );
    }
}

Upvotes: 1

Views: 4497

Answers (3)

Scott Rollan
Scott Rollan

Reputation: 11

If you want something other than "Click Me" alerted:

<h1 onClick={this.changeDimension.bind(this)} data-value="something other"> Click Me</h1>

Then:

alert(event.target.dataset.value)

Upvotes: 1

Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1743

on those cases , i generally pass directly the value as a parameter on the function , especially if i have multiple buttons generated by a loop , for example :

{this.state.dimensions.map(dimension => <h1 onClick={() => this.changeDimension(dimension)}>{dimension.value}</h1>)}

Upvotes: 0

Tamas Szoke
Tamas Szoke

Reputation: 5542

The value attribute is not set in:

<h1 onClick={this.changeDimension.bind(this)}> Click Me</h1>

If you need the "Click Me" text then use:

alert(e.currentTarget.innerHTML);

Upvotes: 3

Related Questions