Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Ivan Baranov
Ivan Baranov
11,344 Points

React getting correct prop type from an input

I want to get a number from an input, even though everything works just fine, it's just feels wrong. Here is what I got from a console: Warning: Failed prop type: Invalid prop numOne of type string supplied to NumOne, expected number. in NumOne (created by App) in App

///// My code:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './app.sass';

import NumOne from './components/NumOne';
import NumTwo from './components/NumTwo';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      numOne: 0,
      numTwo: 0,
      output: 0
    };
  }
handleNumChangeOne = e => {
  this.setState({
    numOne: e.target.value
  })
}

handleNumChangeTwo = e => {
  this.setState({
    numTwo: e.target.value
  })
}

handleSubmit = e => {
  e.preventDefault();
  this.setState({output: parseFloat(this.state.numOne) + parseFloat(this.state.numTwo)})
}


  render() {
    return(
      <div className="calc">
        <h1>This is going to be a React Calculator!</h1>
        <form onSubmit={this.handleSubmit}>
          <NumOne numOne={this.state.numOne} handleNumChangeOne={this.handleNumChangeOne}/>
          <NumTwo numTwo={this.state.numTwo} handleNumChangeTwo={this.handleNumChangeTwo}/>
            <br />
            <input type="submit" value="Submit"/>
            <span>{this.state.output}</span>
        </form>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

numTwo component:

import React from 'react';
import PropTypes from 'prop-types';

const NumOne = props =>
<label>
  <input
  type="number"
  name="numOne"
  value={props.numOne}
  onChange={props.handleNumChangeOne}/>
</label>;

NumOne.propTypes = {
  numOne: PropTypes.number.isRequired,
  handleNumChangeOne: PropTypes.func.isRequired
}

export default NumOne;

numOne component:

import React from 'react';
import PropTypes from 'prop-types';

const NumTwo = props =>
  <label>
    <input
      type="number"
      name="numTwo"
      value={props.numTwo}
      onChange={props.handleNumChangeTwo}/>
  </label>;


NumTwo.propTypes = {
  numTwo: PropTypes.number,
  handleNumChangeTwo: PropTypes.func
}

export default NumTwo;