tfantina
tfantina

Reputation: 815

React get a Button's id in

I'm trying to pass the ID of a button, when it's clicked, to a function but I've been unable to get anything to happen. I'm going to put some logic into the function that will change the font size based on if the user hits "increaseButton" or "decreaseButton" which is easy enough, but I'm having trouble being able to get the id for the buttons. Component

fontSize(e) {
      console.log(e.target.id);
 }

Render

 <button id="decreaseButton"  hidden={isHidden} onClick {this.fontSize.bind(this)}>-</button>

Upvotes: 0

Views: 684

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

As you have mentioned, you are going to change font size based on increase or decrease actions. Why don't you use both buttons and bind them with their specific actions so you don't have to rely on attributes of any kind?

const Button = ({ children, onClick }) => <button onClick={onClick}>{children}</button>

class App extends React.Component {
  constructor() {
    super()

    this.state = {
      fontSize: 16,
    }

    this.handleDecrease = this.handleDecrease.bind(this)
    this.handleIncrease = this.handleIncrease.bind(this)
  }

  handleDecrease() {
    // Sample rule: fontSize should no be less than 10
    this.setState({ fontSize: Math.max(this.state.fontSize - 1, 10) })
  }
  
  handleIncrease() {
    // Sample rule: fontSize should not be greater than 30
    this.setState({ fontSize: Math.min(this.state.fontSize + 1, 30) })
  }

  render() {
    return (
      <div>
        <Button onClick={this.handleDecrease}>
          Decrease font
        </Button>
        <Button onClick={this.handleIncrease}>
          Increase font
        </Button>
        
        <div>Current fontSize: {this.state.fontSize}</div>
        <div style={{ fontSize: this.state.fontSize }}>Preview</div>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

Upvotes: 1

Related Questions