Reputation: 879
I would like to include the showTimeSelect property in the ReactDatePicker component below if the {type} === 'dateTime', otherwise I want to omit it, but it's not currently working. I'm a React noob, so would appreciate guidance on getting this to work.
The purpose of this is because I'm using ReactDatePicker in a form and sometimes I would like it to display as a date picker and at other times I want it to show as a time picker. The way to do this is by adding in one property to the ReactDatePicker component, namely showTimeSelect.
import React from 'react';
import ReactDatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { Controller } from 'react-hook-form';
function FormDate({ name, question, register, control, type }) {
const varShowTimeSelect = ({ type }) =>
({ type } === 'dateTime' ? { showTimeSelect } : {});
return (
<div className="form-group">
<label htmlFor={name}>{question}</label>
<div className="input-group date col-xs-5">
<Controller
as={
<ReactDatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select date"
{varShowTimeSelect} //Conditionally show showTimeSelect prop
/>
}
control={control}
name={name}
ref={register}
id={name}
valueName="selected"
onChange={([selected]) => selected}
/>
</div>
</div>
);
}
export default FormDate;
Many thanks,
Katie
Upvotes: 0
Views: 466
Reputation: 13652
In addition to what Dennis suggested (which I think is the better solution in this case), if you want to conditionally not pass the prop at all, you'd want to do use spread:
function FormDate({ name, question, register, control, type }) {
const showTimeSelectProps = type === 'dateTime' ? { showTimeSelect: true } : {};
return (
<div className="form-group">
<label htmlFor={name}>{question}</label>
<div className="input-group date col-xs-5">
<Controller
as={
<ReactDatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select date"
{...showTimeSelectProps} //Conditionally show showTimeSelect prop
/>
}
control={control}
name={name}
ref={register}
id={name}
valueName="selected"
onChange={([selected]) => selected}
/>
</div>
</div>
);
}
Upvotes: 1
Reputation: 53874
Add the condition within the property value as showTimeSelect
accepts a boolean
type:
<ReactDatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select date"
showTimeSelect={type === 'dateTime'}
/>
function FormDate({ name, question, register, control, type }) {
return (
<div className="form-group">
<label htmlFor={name}>{question}</label>
<div className="input-group date col-xs-5">
<Controller
as={
<ReactDatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select date"
showTimeSelect={type === 'dateTime'}
/>
}
control={control}
name={name}
ref={register}
id={name}
valueName="selected"
onChange={([selected]) => selected}
/>
</div>
</div>
);
}
Upvotes: 2