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?
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?
Share Improve this question asked Aug 30, 2016 at 23:21 Jason ChenJason Chen 2,5776 gold badges27 silver badges47 bronze badges4 Answers
Reset to default 3You 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
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;
you can you defaultValue attribute
<input type="text" ref={nameRef} name="name" placeholder="Enter name..." defaultValue={...yourvalue} />
I solved it by assigning the initial value in ponentDidMount. I was receiving initial value through props. Take a look.