The worm
The worm

Reputation: 5888

Setting a default value to an input field in React?

I want to set an input field a user can type into with a £ sign fixed into that field. The user should not be able to delete or change this sign, but the user should be able to modify what comes after.

e.g.

  1. initial £
  2. user adds 10, result: £10
  3. user modified changes 10 -> 5000, result: £5000
  4. user deletes everything in the field, result: £ remains

The placeholder tag does not work as this is not visible when entering something in the field. The default value is also not doing quite what I want.

Place your stake: <input type="text" onChange={this.handleStakeChange}/>

Upvotes: 1

Views: 3826

Answers (3)

Giorgio Bozio
Giorgio Bozio

Reputation: 3037

You can avoid styles and just do plain React. Input values should come from state and change should give a new state. It's the concept of "controlled components"

https://facebook.github.io/react/docs/forms.html#controlled-components

In this way you have full control on what goes and comes from input elements. The state is the source of truth.

var StakeInput = React.createClass( {
getInitialState: function(){
  return {stake: ''}
},
handleStakeChange: function(e){
  const stakeInputValue = e.target.value.replace(/£/g, '').trim()
  this.setState({
    stake: stakeInputValue
  });
},
render: function(){
  return (
    <div>
    Place your stake: 
      <input type="text" value={'£ ' + this.state.stake}
        onChange={this.handleStakeChange}/>
    </div>
  )

    }
});
React.render(<StakeInput />, document.getElementById('output'));

http://jsbin.com/jemasub/edit?html,js,output

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

You can do so easily with CSS, and a background image:

.pounds-input {
  padding: 0 0 0 20px;
  background: url(https://cdn1.iconfinder.com/data/icons/business-finance-1-1/128/currency-sign-pound-128.png) no-repeat;
  background-size: 12px 12px;
  background-position: 2px 2px;
}
<input class="pounds-input" type="number" />

Upvotes: 3

mlunoe
mlunoe

Reputation: 4490

You can do this by simply placing an element with the symbol next to the input field and setting padding-left (or text-indent) on the input field itself:

.currency {
  position: relative;
  left: 15px;
}
input {
  padding-left: 12px;
  /* or text-indent: 12px; */
}
<label>Place your stake:</label>
<span class="currency">£</span>
<input type="number" />

Upvotes: 2

Related Questions