3

So I mapped an array to buttons having the value to be the element of the array, but when I log the event.target.value to the console, I get undefined sometimes.

When I click each button, I get this in the console

0
1
2
3
undefined
undefined
undefined
6
7
undefined
9

Here's the code I have

class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      selected: '',
      numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    }
  }

  handleClick = (event) => {
    event.preventDefault()
    console.log(event.target.value);

  }

  render() {
    return (
      <div>
          <Container>
            <Row>
              {this.state.numbers.map(i => {
                return (
                  <Col key={i.toString()}>
                    <ButtonToolbar>
                      <Button
                        value={i}
                        onClick={this.handleClick}
                      >
                        <h3>{i}</h3>
                      </Button>
                    </ButtonToolbar>
                  </Col>
                )
              })}
            </Row>
          </Container>
      </div>
    );
  }
}
Vencovsky
  • 28,550
  • 17
  • 109
  • 176

1 Answers1

3

That's because sometimes you are clicking on the Button component, and sometimes on the nested h3 element, and event.target.value of h3 is undefined.

Best to pass the value within the onClick handler.

...
onClick={(event) => this.handleClick(event, i)}
...
handleClick = (event, i) => {
  console.log(i);
}

(You may want to omit the event value, if you have no use for it.)

OR if you want to stick to your current implementation, you can access the value via event.currentTarget.value. currentTarget vs target

dw_
  • 1,707
  • 1
  • 7
  • 13
  • 1
    Oh this is just a sample code I wrote up, there're more codes in my actual code. Thanks a lot. This fixed the problem in my page – Leslie Zhou Dec 04 '19 at 19:25