Reputation: 755
I'm using react date selector plugin called react-flatpickr. When I want the flatpickr to be disabled, I need to set a prop called "disabled" on the Flatpickr component. disabled is not a boolean that can be set to true or false. disabled is a property without a value. Is there a way to initialize the Flatpickr component with the disabled prop only when readOnly is true, instead of this horribly duplicated code?
getFlatPickr(id, ref, defaultDate, minDate, readOnly){
if (readOnly) {
return (
<Flatpickr
id={id}
name={id}
disabled
className={"form-control"}
placeholder={"MM/DD/YYYY HH:MM AM/PM"}
options={{
enableTime: true,
dateFormat: this.state.flatpickrDateFormat,
}}
/>
);
} else {
return (
<Flatpickr
id={id}
name={id}
className={"form-control"}
placeholder={"MM/DD/YYYY HH:MM AM/PM"}
options={{
enableTime: true,
dateFormat: this.state.flatpickrDateFormat
}}
/>
);
}
}
Upvotes: 1
Views: 410
Reputation: 7492
Sure, simply set the disabled
prop directly to your readOnly
variable :
getFlatPickr(id, ref, defaultDate, minDate, readOnly) {
return (
<Flatpickr
id={id}
name={id}
disabled={readOnly}
className={"form-control"}
placeholder={"MM/DD/YYYY HH:MM AM/PM"}
options={{
enableTime: true,
dateFormat: this.state.flatpickrDateFormat
}}
/>
);
}
}
Even shorter syntax :
getFlatPickr = (id, ref, defaultDate, minDate, readOnly) => (
<Flatpickr
id={id}
name={id}
disabled={readOnly}
className="form-control"
placeholder="MM/DD/YYYY HH:MM AM/PM"
options={{
enableTime: true,
dateFormat: this.state.flatpickrDateFormat
}}
/>
)
Upvotes: 2