Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a placeholder with a number input in React?

I have a number input in a form like follows :

<input
  type="number"
  id="weight"
  onChange={this.handleChange}
  value={this.state.weight}
  placeholder="Enter weight…"
/>

How can I have a placeholder phrase display on it ?

If I initialy set this.state.weight to value 0, then no placeholder displays.

If I set it to null the placeholder displays but get this ugly warning

Warning: value prop on input should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components.

like image 389
Lev Avatar asked Sep 19 '18 15:09

Lev


2 Answers

You can use: weight: ""

class App extends React.Component {
  state = {
    weight: "",
  };

  handleChange = e => this.setState( { weight: e.target.value } )

  render() {
    return (
      <div>
        <input
          type="number"
          id="weight"
          onChange={this.handleChange}
          value={this.state.weight}
          placeholder="Enter weight…"
        />
      </div>
    );
  }
}

ReactDOM.render( <App />, document.getElementById( "root" ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

If you want a number at the end of the change, then you can use:

handleChange = e => this.setState( { weight: e.target.valueAsNumber } )
like image 147
devserkan Avatar answered Sep 29 '22 19:09

devserkan


	class App extends React.Component{
	  constructor(props){
		super(props);
    this.state = {weight:undefined}
	  }
	  render(){
		return(
			<input
          type="number"
          id="weight"
          value={this.state.weight}
          placeholder="Enter weight…"
        />
		)
	  }
	}

	ReactDOM.render(
	<App/>,
	document.getElementById("root")
	);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Define weight with undefined that will work.

this.state = {
    weight:undefined
};
like image 20
Amruth Avatar answered Sep 29 '22 21:09

Amruth