Reputation: 117
I'm new to react and I don't know some basic things so I got confused about this problem. Here's the code:
import React, {Component} from 'react';
import './css/style.css'
class Calculator extends React.Component {
constructor(props){
super(props);
}
click = ()=>{
console.log(button.value)
}
render(){
return(
<div>
<button value='1' onClick = {this.click()}>1</button>
</div>
)
}
}
export default Calculator
How can I get value of button in my console? should I create button class or maybe there's more efficient method to do it?
Upvotes: 0
Views: 430
Reputation: 370769
If you have the click
method accept an argument, and pass this.click
as a callback instead of invoking it immediately on load or in an anonymous wrapper function, you can reference the event target to get to the button, and from that get to the value:
class Calculator extends React.Component {
click = (e) => {
console.log(e.target.value);
}
render(){
return(
<div>
<button value='1' onClick = {this.click}>1</button>
</div>
)
}
}
ReactDOM.render(<Calculator />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Upvotes: 1