V
V
Vladimir Vlasyuk2018-07-12 07:32:38
JavaScript
Vladimir Vlasyuk, 2018-07-12 07:32:38

How to put default value in input type="number"?

There are 2 inputs with number type, I need to set the initial value to each input from the props, for example this.props.min in the first input, but the problem is that when I try to clear the value of the input, the value from the props automatically becomes, and I need that if the value were set only 1 time during rendering, then it could be changed / cleared.
PS. props by apishka from redax

import React from 'react'

class MobileCountInput extends React.Component {
  constructor(props) {
    super(props)
    this.handleChangeMin = this.handleChangeMin.bind(this)
    this.handleChangeMax = this.handleChangeMax.bind(this)
  }

  state = {
    valueMin: '',
    valueMax: ''
  }

  handleChangeMin(e) {
    let value = parseFloat(e.target.value)
    this.setState({
      valueMin: value
    })
  }

  handleChangeMax(e) {
    let value = parseFloat(e.target.value)
    this.setState({
      valueMax: value
    })
  }

  render() {
    let valmin = this.state.valueMin
    
    return (
      <div>
                              <input
        type="number"
        value={valmin || this.props.min}
        onChange={(e) => this.handleChangeMin(e)}
                              />
        <input
          type="number"
    			  value={this.state.valueMax}
          onChange={(e) => this.handleChangeMax(e)}
        />
      </div>
    )
  }
}

export default MobileCountInput

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-07-12
@Skajinet

You just need to set the initial state

state = {
    valueMin: this.props.min || '',
    valueMax: ''
  }

// в рендере убрать условие у первого инпута в value
<input
  type="number"
  value={valmin}
  onChange={(e) => this.handleChangeMin(e)}
/>

codesandbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question