I am using react-datepicker and have a select with 4 options, I need to show the calendar only when option number 3 is selected. Here's the code I have so far.
const [startDate, setStartDate] = useState(new Date())
<div className="input-block"> <label htmlFor="status">Status</label> <select id="status" name="status" required> <option value="1">Aguardando Disponibilidade</option> <option value="2">Aguardando Agendamento</option> <option value="3">Ativação Agendada</option> <option value="4">Ativação Efetuada</option> </select> <div className="calendar"> <DatePicker className="calendar-input" selected={startDate} onChange={(date) => setStartDate(date)} showTimeSelect timeFormat="HH:mm" dateFormat="dd/MM/yyyy HH:mm " /> </div> </div>
import React, { useState } from 'react';
const YourComp = () => {
const [selectedValue, updateSelectedValue] = useState();
const [startDate, setStartDate] = useState(new Date())
const onSelectChange = ({ target: { value } }) => updateSelectedValue(value);
return (
<div className="input-block">
<label htmlFor="status">Status</label>
<select
id="status"
name="status"
required
onChange={onSelectChange}
>
<option value="1">Aguardando Disponibilidade</option>
<option value="2">Aguardando Agendamento</option>
<option value="3">Ativação Agendada</option>
<option value="4">Ativação Efetuada</option>
</select>
{
selectedValue === '3'
? (
<div className="calendar">
<DatePicker
className="calendar-input"
selected={startDate}
onChange={(date) => setStartDate(date)}
showTimeSelect
timeFormat="HH:mm"
dateFormat="dd/MM/yyyy HH:mm "
/>
</div>
)
: null
}
</div>
)
}
The above mentioned code should resolve your issue. The idea is to put a conditional check to render DatePicker component. React Official Doc - Conditional Rendering
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.