Reputation: 2577
So my code looks like so:
stockconfirmbuy: function(){
var totalbuyval = this.refs.stockpriceref.innerHTML * this.refs.stockdnum.value;
return (<div>
<input type="number" value="1" ref="stockdnum" />
<p>Your Total:</p>
<p>${totalbuyval}</p>
</div>);
},
My problem here is that I get a Cannot read property 'value' of undefined
error. This refers to my input type="number"
.
However, I have been trying to give my input a default value so that this does not occur. I gave it a default value=1
, but this does not seem to satisfy the ref.
So I am wondering what I need to do to set a default ref value. Or should I be using state?
Upvotes: 3
Views: 11338
Reputation: 1
you can you defaultValue attribute
<input type="text" ref={nameRef} name="name" placeholder="Enter name..." defaultValue={...yourvalue} />
Upvotes: 0
Reputation: 11
I solved it by assigning the initial value in componentDidMount. I was receiving initial value through props. Take a look.
Upvotes: -1
Reputation: 44068
You should absolutely be using state here, set default state value with getInitialState()
for both stockdnum
and stockpriceref
You then can render the value from state, e.g. <input type="number" value={this.state.stockdnum}/>
. Note that this will cause the input to be read-only unless you set up an onChange
to update state. Read more about this here
I doubt you need refs at all for this, and in fact you should avoid them if possible. They're more for providing raw DOM refs to non-React APIs (e.g. jQuery or TweenLite or something)
Also, string refs as you are using them there will likely be removed in the future anyway
Upvotes: 3
Reputation: 5859
I have been trying to give my input a default value so that this does not occur
you can do something like this :
var defaultRef = typeof this.refs.stockdnum.value !== "undefined" ? this.refs.stockdnum.value : defaultValue;
var totalbuyval = this.refs.stockpriceref.innerHTML * defaultRef;
Upvotes: 2