1

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;

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

so that would go in like so, right? ` handleClick() { this.setNumStars(parseInt(this.state.numStars, 10)) }`
it's very close to working. I enter in the number and hit submit, nothing happens until I enter in another number (into the text area) and then the previous number populates. So if I type in 100 and hit submit, nothing. But then if I type in 20, then 100 populates. (and so on)
I assume you base your observations on visible this.pulse elements. Right now the pulse elements will always be one render behind the registered value, the easiest way to solve it would be calling this.forceUpdate() at the end of setNumStarts method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.