Jason Chen Jason Chen - 11 months ago 62
React JSX Question

Set a default ref value on React?

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>

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
, 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?

Answer Source

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