I am trying to set focus on react datepicker when enter is pressed on earlier component(input filed). I read a official documentation, and example with simple field is worked, but when I change with DatePicker I get a old error
TypeError: this.inputAccountDate.focus is not a function
My function is:
function CustomDatePicker(props) {
return (
<div>
{/* <input ref={props.innerRef} /> */}
<DatePicker className="form-control"
placeholderText="Izaberite datum"
dateFormat="dd/MM/yyyy"
maxDate={new Date()}
ref={props.innerRef}
/>
</div>
);
}
And snippet code from class with form is:
<Col className="pr-md-1" md="3">
<FormGroup >
<label>Datum računa</label>
<div>
<CustomDatePicker
innerRef={(input) => { this.inputAccountDate = input }}
/>
</div>
</FormGroup>
</Col>
Component where I call a function to set focus is
<Col className="pr-md-1" md="3">
<FormGroup>
<label>Broj računa</label>
<Input style={{'borderColor':'lightgray', 'fontSize':'14px'}}
innerRef={(input) => { this.inputAccountNumber = input }}
onKeyDown={this.focusAccountDate}
placeholder="Br.računa"
type="text"
value={this.state.accountNumber || (header === null ? "" :
header.account_number) }
onChange={this.changeAccountNumber}
onFocus={(e)=>e.target.select()}
required
/>
</FormGroup>
</Col>
Function which managing a focus is
focusAccountDate = (e) => {
if(e !== undefined) {
if(e.key === 'Enter') {
this.inputAccountDate.focus()
}
}
}
and inputAccountDate is this.inputAccountDate = React.createRef()
Use setFocus()
instead of focus
. There is no focus
in DatePicker
In functional Component, the passing ref reference with props is not a valid way. You need to know Forwarding Ref
Your CustomDatePicker should be changed like the following.
function CustomDatePicker(props, ref) {
return (
<div>
<DatePicker className="form-control"
placeholderText="Izaberite datum"
dateFormat="dd/MM/yyyy"
maxDate={new Date()}
ref={ref}
/>
</div>
);
}
export default React.forwardRef(CustomDatePicker)