sthig
sthig

Reputation: 469

React - input value to generate a number not working

I'm trying to learn React and have gotten stuck trying to have an input take in a number then pass that number when the button submit is hit. Most of this works (below) however when I hit submit, my number is converted to a string and I don't know what. Any help or guidance here would help, thank you

    import React from 'react';
import Stars from './star'

class StarMaker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      numStars: 200,
    }
  }
  setNumStars(num) {
    console.log(typeof num);
    const numPulses  = [...Array(num).keys()];
    console.log(numPulses);
    this.pulses = numPulses.map(i => this.generatePulse(i));
  }

  handleClick() {
    this.setNumStars(this.state.numStars)
  }

  handleChange(e) {
    console.log(e);
    this.setState({
      numStars: Number(e.target.value)
    })
  }

  getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  generatePulse(i) {
    const props = {
      key: i,
      top: this.getRandomNumber(-385, 556),
      left: this.getRandomNumber(1, 2430),
      scale: `scale(${this.getRandomNumber(1, 2)})`,

    }
    return (<Stars {...props} />)
  }
  componentWillMount() {
    const numPulses  = [...Array(this.state.numStars).keys()];
    this.pulses = numPulses.map(i => this.generatePulse(i));
  }
  render() {
    console.log('render');
    return (
      <div>
        {this.pulses}
        <input value={this.state.numStars} onChange={this.handleChange.bind(this)} type="number"></input>
        <button onClick={this.handleClick.bind(this)}>Submit</button>
      </div>
    );
  }
}

export default StarMaker;

Upvotes: 1

Views: 2526

Answers (1)

Nhor
Nhor

Reputation: 3940

The input value in HTML will always be a string, no matter what type will you specify. Having said that, whenever you need to use a number data type instead of string, you have to cast it explicitly, basically by parsing the numeric value from the string:

parseInt(this.state.numStars, 10);

Upvotes: 1

Related Questions