user10182767
user10182767

Reputation:

Getting value of input in React and checking it

I have an input field and a button. I want to make so that if a user enters a value in the input field that is a number when he clicks the button a div with information should appear. Right now when the button is clicked it loads my data, but it works even if the input is empty. How can I properly get the value from the input, check if its a number and if it is indeed a number the div should display the info, here is what I made so far:

class CardCheck extends Component {
  constructor(props) {
    super(props);
    this.state = { showMessage: false };
  }

_checkValue() {
  if (evt.taget.value != number) {
    this.setState(prevState => ({
      showMessage: !prevState.showMessage
    }));
  } else {
    alert("Your card id can consist only of numbers!")
  }
}

  _showMessage = () =>
    this.setState(prevState => ({
      showMessage: !prevState.showMessage
    }));
  render() {
    return (
      <div>
        <div className="newsletter-container">
          <h1>Enter the ID of your card:</h1>
          <div className="center">
            <input type="number" onChange={(evt) => { console.log(evt.target.value)}} />
            <input type="submit" value="Check" onClick={this._showMessage {this._checkValue} />
          </div>
          <div />
          {this.state.showMessage && (
            <div className="results">
              <h2 className="green-heading">Your card is valid in the following places:</h2>
              <p>Magic Auto Spa</p>
              <p>Ivans auto shop</p>
              <p>AutoHouse Sofia</p>
              <p>Bankya Auto Palace</p>
              <button className="close" onClick={this._showMessage}>
                Close
              </button>
            </div>
          )}
        </div>
        <h1>Offers:</h1>
      </div>
    );
  }
}

export default CardCheck; 

I tried obtaining the value with the onChange event, check it's type with an if statement and attach that event as a second onClick but it does not work

Upvotes: 0

Views: 191

Answers (2)

Anandhu
Anandhu

Reputation: 827

First, you have an error in
<input type="submit" value="Check" onClick={this._showMessage{this._checkValue} />
Next,
<input> Boxes in React works a little bit differently. Check out this link

Upvotes: 0

John H
John H

Reputation: 14655

You have a typo in your code:

_checkValue() {
  if (evt.taget.value != number) {
  // -------^ should be target

Also, Number.isNaN would be a more robust comparison.

Upvotes: 2

Related Questions