MemoryLeak MemoryLeak - 1 month ago 6
React JSX Question

how to pass the value of one input to another input's onBlur event in reactjs?

I have two date time fields on reactjs form as

<div>
<input type="text" name="startdate" value={this.state.startDate} onBlur={this.validateStartDate} />
<input type="text" name="enddate"value={this.state.endDate} onBlur={this.validateEndDate}/>
</div>


I want to validate the startdate, whether it is less than endDate or not,
How to pass the endDate value to the validateStartDate function?
or
If there is a better way to validate the input date fields, please provide the same.

Answer

I see you're storing your endDate as a state. So, when the user blurs startDate call validateStartDate. In that function, use the endDate state value to validate.

See the pseudo code

<div>
   <input type="text" name="startdate" value={this.state.startDate}  onBlur={this.validateStartDate} /> 
    <input type="text" name="enddate"value={this.state.endDate} onBlur={this.validateEndDate}/> 
</div>

function validateStartDate(){
   //check this.state.startDate < this.state.endDate
}

Or, you can use refs to get the endDate value.

<div>
   <input type="text" ref="startDate" name="startdate" value={this.state.startDate}  onBlur={this.validateStartDate} /> 
    <input type="text" ref="endDate" name="enddate"value={this.state.endDate} onBlur={this.validateEndDate}/> 
</div>

function validateStartDate(){
   var startDate= ReactDOM.findDOMNode(this.refs.startDate).value
   var endDate = ReactDOM.findDOMNode(this.refs.endDate).value
   //check startDate < endDate
}

Hope this helps!