Getting the date from a Bootstrap React form - javascript

How do I extract a yyyy-mm-dd timestamp from the following?
handleDateChange = e => {}
<Form.Group as = {Col}>
<Form.Control
type = "date"
value = { this.state.closingDate }
onChange = { this.handleDateChange }
/>
</Form.Group>
At the moment e.timeStamp gives me a four or five digit number.

Try this:
handleDateChange = e => {
const date = new Date(e.target.value);
const timestamp = date.getTime();
console.log(timestamp)
this.setState({
closingDate: e.target.value
})
}

Related

DatePicker throws Uncaught TypeError of undefined in onChange

I have a DatePicker which is throwing the following error message: Uncaught TypeError: Cannot read properties of undefined (reading 'value').
My data is being pulled from an API where some items date field is null. Initial render of the page is fine, where the TextFields and 2 empty date pickers display, but when I input a date, the error is thrown.
When an item does have a date value, it is returned from the API like this Aug 12 2020 12:00AM
I want to disregard the time and append the date to the date picker when the there is a date present. If there is no date, I want to append todays date.
The following code will display a TextField or a DatePicker based on the value of FieldType.
Here is my API request:
const [details, setDetails] = useState("");
const fetchDetails = async () => {
setBusy(true);
setDetails(await fetch(`/fiscalyears/FY2023/intakes/${params.id}/details`).then((response) => response.json()));
setBusy(false);
};
This is how I switch between TextFields, Selects and the DatePicker:
return (
<Box>
{details["fields"]?.map((row, index) => {
if (row?.FieldType === "Text" || row?.FieldType === "Decimal" || row?.FieldType === "Number") {
return (
<TextField
value={row?.Value || ""}
onChange={(e) => {
setDetails((prev) => {
const update = [...prev.fields];
update[index] = {
...update[index],
Value: e.target.value,
};
return { ...prev, fields: update };
});
}}
/>
);
}
if (row?.FieldType === "Date") {
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label={row?.FieldName || ""}
renderInput={(params) => <TextField {...params} />}
value={row?.Value || ""}
onChange={(e) => {
setDetails((prev) => {
const update = [...prev.fields];
update[index] = {
...update[index],
Value: e.target.value,
};
return { ...prev, fields: update };
});
}}
/>
</LocalizationProvider>
);
}
})}
</Box>
)

Input type number with comma React

I have a question about input type number in React.
I need to display dot separator if user enter number with comma.
Like this
11,2
Should convert to
11.2
How I can convert this number?I try
value.replace(/,/g, '.')
But this isn't working.I still see comma in my input.
PS:
This how I handle input
<input
type="number"
placeholder='Input'
name="inputValue"
step="0.01"
inputMode="decimal"
id='inputValue'
min="0"
value={inputValue}
onChange={handleChange}
/>
And this is my handleChange function
const handleChange = e => {
let { name, value } = e.target;
value = value.replace(/,/g, '.');
setData(prevState => ({ ...prevState, [name]: value}));
}
Try this code:
const Number = "11,1";
console.log(Number.replace(/\,/, "."));
//Now your handleChange function will look like this:
const handleChange = e => {
let { name, value } = e.target;
value = value.replace(/\,/, ".");
setData(prevState => ({ ...prevState, [name]: value}));
}

Assigning value from setState to a variable in React js component

In the middle of a slightly long component which is basically a split date input (3 inputs for DD/MM/YYYY) - I think my approach is correct for the most part, but I'm struggling with my getDate function. The idea is that the currentDate is passed into this function (whatever has been entered in the keyboard), like so:
const handleValueChange = (date?: string) => {
onValueChange(getDate(date));
};
In the getDate function I want to take the values from selectedDay, selectedMonth & selectedYear and assign them to variables so that they can then be joined using the .join method and a valid date like "28-08-2022" can be returned.
Can anyone advise on a best possible approach?
const getDate = (date?: string): string => {
if (date) {
/* need to take value for DD/ MM / YYYY and store them in
individual variables that can then be used in an array or
something similar with .join to return a
joined up date like "28-09-2022" */
}
return "";
};
const DateInput = ({
dateInputValue,
dateInputFormat,
className,
inFilterContext,
onChange,
onValueChange,
value = "",
type = "text",
readOnly = false,
disabled = false,
placeholder,
mindate,
maxdate,
...inputProps
}: Props) => {
const [intialDayValue, initialMonthValue, initialYearValue] =
dateInputValue.split("-");
const [selectedDay, setSelectedDay] = useState(intialDayValue || "");
const [selectedMonth, setSelectedMonth] = useState(initialMonthValue || "");
const [selectedYear, setSelectedYear] = useState(initialYearValue || "");
const handleValueChange = (date?: string) => {
onValueChange(getDate(date));
};
// handle date input change event - DAY
const handleDayChangeEvent = (e: SyntheticInputEvent<any>) => {
const currentDate = e.target.value;
setSelectedDay(currentDate);
handleValueChange(currentDate);
};
// handle date input change event - MONTH
const handleMonthChangeEvent = (e: SyntheticInputEvent<any>) => {
const currentDate = e.target.value;
setSelectedMonth(currentDate);
handleValueChange(currentDate);
};
// handle date input change event - YEAR
const handleYearChangeEvent = (e: SyntheticInputEvent<any>) => {
const currentDate = e.target.value;
setSelectedYear(currentDate);
handleValueChange(currentDate);
};
return (
<StyledInputGroup>
<label htmlFor={`${name}_day`}>
<span>Day</span>
<StyledInput
{...inputProps}
type={type}
maxLength="2"
disabled={disabled}
readOnly={readOnly}
value={selectedDay}
onChange={handleDayChangeEvent}
onValueChange={handleDateSelectDay}
/>
</label>
<label htmlFor={`${name}_month`}>
<span>Month</span>
<StyledInput
{...inputProps}
type={type}
maxLength="2"
disabled={disabled}
readOnly={readOnly}
value={selectedMonth}
onChange={handleMonthChangeEvent}
onValueChange={handleDateSelectMonth}
/>
</label>
<label htmlFor={`${name}_year`}>
<span>Year</span>
<StyledInput
{...inputProps}
type={type}
maxLength="4"
disabled={disabled}
readOnly={readOnly}
value={selectedYear}
onChange={handleYearChangeEvent}
/>
</label>
</StyledInputGroup>
);

How to set moment to empty depending on select

I want to set the start date and end date to undefined when select item change, I have used useEffect to handle this but on the UI the date don't set to empty.
this my code
const [startDate, setStartDate] = useState<moment.Moment>();
const [endDate, setEndDate] = useState<moment.Moment>();
const onChange = useCallback(
(value) => {
setEndDate(value);
},
[setEndDate, setIsMoreThenBalance]
);
const onChangeStartDate = useCallback(
(value) => {
setStartDate(value);
},
[setStartDate]
);
useEffect(() => {
if (selectedLeaveId) {
setStartDate(undefined);
setEndDate(undefined);
}
}, [selectedLeaveId]);
return(
<StyleDatePicker
onChange={(date) => {
onChangeStartDate(date);
}}
disabledDate={disableStartDate}
value={startDate}
format="DD/MM/YYYY"
autoFocus
/>
<StyleDatePicker
onChange={(date) => {
onChange(date);
}}
value={endDate}
disabled={!startDate}
disabledDate={disableEndDate}
$isThereError={isMoreThenBalance}
format="DD/MM/YYYY"
/>
)
the date picker should clear the startDate and endDate every time the select another leave
i have fixed the issue , just add form.resetFileds() here
useEffect(() => {
if (selectedLeaveId) {
setStartDate(undefined);
setEndDate(undefined);
form.resetFileds();
}
}, [selectedLeaveId]); ```
and it's work fine . thank you

ReactJS - Booking Website / Filtering for Date and Price

I am currently working on a project. It is a website for booking rooms like AirBnB or Booking.com
I work with Java Spring as backend and frontend with ReactJs.
Most of the code is running as it should but I still have some problems at filtering for the date (Date Picker in React) and also for the price and the amount of rooms. The Date picker should check the availability of the rooms.
Currently i implemented it with a button but the filters change in running time, so the problem is they are not working together...
Maybe i just show you my code:
import React, { useState } from 'react'
import {useContext} from 'react'
import {RoomContext} from '../context'
import Title from '../components/Title';
import "react-date-range/dist/styles.css";
import "react-date-range/dist/theme/default.css";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import {useHistory} from "react-router-dom";
import axios from 'axios';
//get all unique values
const getUnique = (items, value) => {
// set only accepts unique values
return [...new Set(items.map(item => item[value]))]
}
const getAvailableApartments = (availableApartments, value) => {
return [...new Set(availableApartments)]
}
export default function RoomFilter({rooms}) {
const context = useContext(RoomContext)
//value from my inputs
const [startDate, setStartDate] = useState(new Date());
const history = useHistory();
const [endDate, setEndDate] = useState(new Date());
const [availableApartments, setAvaiableapartments] = useState([]);
const selectionRange = {
startDate: startDate,
endDate: endDate,
key: "selection"
};
function handleSelect(ranges){
setStartDate(ranges.selection.startDate);
setEndDate(ranges.selection.endDate);
}
const {
handleChange,
capacity,
price,
minPrice,
maxPrice,
} = context;
const handleChange2 = (event) => setStartDate(event.target.startDate);
const handleSubmit = event => {
event.preventDefault()
axios
.post("/api/availableapartments", {
startDate: startDate,
endDate: endDate
})
.then((res) => {
setAvaiableapartments(res.data);
console.log(res.data);
})
}
//get people
let people = getUnique(rooms, 'capacity');
people = people.map((item, index) => {
return <option key={index} value={item}>{item}</option>
})
//get apartmentIds
let id = getUnique(rooms, 'id');
id = id.map((item, index) => {
return <option key={index} value={item}>{item}</option>
})
let availableApartment = getAvailableApartments(availableApartments, 'availableApartment');
console.log(availableApartment);
return (
<section className="filter-container">
<Title title="search rooms"/>
<form className="filter-form">
{/*guests*/}
<div className="form-group">
<label htmlFor="capacity">Guests</label>
<select
name="capacity"
id="capacity" value={capacity}
className="form-control"
onChange={handleChange}>
{people}
</select>
</div>
{/* end guests*/}
{/* room price*/}
<div className="form-group">
<label htmlFor="price">
room price ${price}
</label>
<input type="range" name="price" min={minPrice} max={maxPrice} id="price" value={price}
onChange={handleChange} className="form-control"/>
</div>
{/* end room price*/}
{/* room date picker*/}
<div className="form-group">
<DatePicker
selected = {startDate}
onChange = {date => setStartDate(date)}
selectsStart
startDate = {startDate}
endDate = {endDate}
ranges = {[selectionRange]}
/>
<DatePicker
selected = {endDate}
onChange = {date => setEndDate(date)}
selectsStart
endDate = {endDate}
minDate = {startDate}
ranges = {[selectionRange]}
/>
<div>
<button onClick={handleSubmit}>Search Apartments</button>
{availableApartments && availableApartments.map((apartment) => {
return (
<div className="datepickersearch--availableapartments-container-card">
<li>{apartment.apartmentNumber}
</li>
</div>
)
})
}
</div>
</div>
{/* end date picker*/}
</form>
</section>
);
}
I still think the error is within my React Code but maybe it is also relevant to show the test data in my data.sql and the Implementation within the backend.
data.sql
INSERT INTO "reservation" (id, apartment_id, billing_address, check_in_date, check_out_date, has_room, no_guests, payment, price, reservation_number, email)
VALUES (1, 1, 'testreservation', '2021-05-29','2021-06-03', true, 12, true, 12.9, 1234,'admin#vacationhome.com');
Implementation in my AppartmentController
#GetMapping(value = "api/availableapartments")
public List<Apartment> getAvailableApartments(#RequestBody String request)throws JSONException, ParseException {
JSONObject jsonObject = new JSONObject(request);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = format.parse(String.valueOf(jsonObject.getString("startDate")));
Date endDate = format.parse(String.valueOf(jsonObject.getString("endDate")));
return apartmentService.getAvailableApartments(startDate, endDate);
}
OnChange of the date you are updating the state of the start or end dates accordingly which will re-render the component but the data won't change as you are making API call only on submit.
To check is there any problem in the java code you can just console.log data and check whether the data returned is correct only then you can assume the problem is with the react code.
On filter change which functionality is not working can you elaborate on that.

Categories

Resources