How to add date value in a JSON form? [Snippet attached] - javascript

I am making a react app which has the form that consists of basic details and employment details section.
The form is almost done and also I am able to form a JSON structure for different sections.
Complete working example here: https://codesandbox.io/s/nextjs-css-only-carousel-forked-v7gg0
Now for employment details section, I am in the need to include start date and end date as an input field.
So I have made a custom month and year picker and included the same inside the components as monthpicker.js .
And from employment details section I have called the component using the code,
<MonthPicker
value={month}
name="startDate"
label="Start Date"
onChange={setMonth}
/>
Using the following code, the selected value is updated,
const [month, setMonth] = useState(
`${`0${new Date().getMonth() + 1}`.slice(-2)}/${new Date().getFullYear()}`
);
But I can understand this is the place where things needs to be changed but I am not sure of handling it.
File where the monthpicker component included .
Requirement: So if user selects the month and year from the picker, then that particular value needs to get updated in the JSON structure which doesn't happen now.
Eg:
If user selects the month as Jun and year as 2016 then the JSON format will be like,
{
"basicDetails": {
"firstName": "...",
"lastName": "..."
},
"companyDetails": [
{
"companyName": "...",
"designation": "...",
"startDate": "06/2016"
}
]
}
As it is possible to add additional rows, the selected value needs to get added to the respective inputs.
Really stuck for long and need some good help..

#Undefined I'll be using the same code from my answer here and will add the feature you're trying to implement on this post.
The reason why the changes of your MonthPicker component's value is not reflecting to the formValue is because you are passing the setMonth as onChange instead of handleInputChange — basically the changes are stored only on the month state.
Ideally we should be able to use the MonthPicker like below, where we accept an event from the onChange prop that we can use to extract the target.name and target.value properties.
<MonthPicker
label="Start Date"
name="startDate"
onChange={(event) => handleInputChange(index, event)}
/>
I fixed and refactored your MonthPicker component, so that everytime its value change like incrementing/decrementing the year and selecting a month we'll call the onChange prop passing its new value.
Please check the demo below and if you have questions just let me know.

You are calling setMonth on change, but not passing a value:
onChange={(e) => setMonth(e.target.value)}

Related

how to automatically get date in specific format from DatePicker?

I'm using the component DatePicker from antd.
I have currently a Form from antd, in which there's a Form.Item, in which I put the DatePicker.
I want the Form.Item to be given the date in a specific format, lets say YYYY-MM-DD, is there a way to do that?
by giving it the prop format I can choose how it will look like in the UI but I'm trying to make it send back the value by the same format.
I've tried giving it a dateFormat prop with the function
function dateFormat(date) {
return moment(date).format("YYYY/MM/DD");
}
but it doesn't work.
is there a way to do this manipulating the data in the onChange function?
so apparently there's no way to do it in the props,
I've checked and so has #MoaazBhnas.
If anyone somehow finds a way, I'll be looking forward to hear!

vue datepicker returns "1969" value

I have implemented the vue datepicker component as shown in the link below:
https://github.com/ReproNim/reproschema-ui/blob/master/src/components/Inputs/YearInput/YearInput.vue
when this component is answered and i move to a different page and revisit this page where the datepicker is, the value gets modified to "1969".
in the mounted method (line 53 in above link), i check for any initialized value. if present, it is assigned to data "input". i checked the init value and it is correct (it has the previously answered value) but on screen the component shows "1969".
can someone help as to why this happens?
The code looks correct for the most part.
Perhaps the input value is not formatted correcty so the default of 'epoch' is used.
Or your typos are causing the problem...
lang=selected_language and :initialView=inputType and :minimumView=inputType
<datepicker placeholder="Select Date" v-model="input" :lang='selected_language'
:disabledDates="dateParam.disabledDates" :format="customFormatter"
:minimumView='inputType' :maximumView="'year'" :initialView='inputType'
></datepicker>
I finally was able to solve this question!
when the answered value is "year", eg. 1990, in the mounted lifecycle hook, before assigning it to the data variable, I need to convert the 'year' value to a date object.

How to render Date Object in React Redux?

I am working on a booking app in learning purposes. I'm using React, Redux and React DatePicker.
Basically, everything works well, except for passing the Date object as a prop. It throws an error message:
Error: Objects are not valid as a React child (found: Sat Nov 09 2019 16:09:32 GMT+0500 (Yekaterinburg Standard Time)). If you meant to render a collection of children, use an array instead.
I know that React can't render objects, so I tried to use "toString()" method in reducer but it didn't help. I guess I should use this method in DatePicker but I don't know how.
<DatePicker
selected={this.props.date}
dateFormat="LLL"
onChange={(day) => {this.props.setDate(day)}}
locale="ru"
inline
/>
Tell me, please, where do I need to add toString() method, so that when I select a date in the calendar, the Date object is a string and my application works fine.
The best way to turn your date object into a string is going to depend on what information you want to display. Try .toLocaleDateString() to get a string that's formatted to the way dates are commonly written in the user's custom.
Check out MDN's Date documentation for more options (you'll probably want one listed under the 'conversion getter' section)
For how to integrate this into React, you don't need to do the conversion in your reducer. Redux can store date objects just fine, then you can call the conversion method of choice inside your component.
Imagine, for instance, a todo item component which takes in a Date object as a prop. This object, in your case, would come from redux.
const TodoItem = ({ task, dueDate }) => (
<div>
<h2>{task}</h2>
<span>{dueDate.toLocaleDateString()}</span>
</div>
);
The other option would be to call .toLocaleDateString() inside of your mapStateToProps function

React Final Form Pass Additional Parameters to Form State

React Final Form uses a render prop pattern in its form component, and I am trying to understand how I can modify it to pass it additional arguments.
According to it's documentation, it passes the following props to the render function - including (crucially) the FormState.
Let's take a look at my particular implementation, focusing on the render function:
<Form
onSubmit={() => {console.log("wow coolio you submitted a form!")}}
initialValues={initData}
validate={validateMyForm}
render={({ handleSubmit, reset, submitting, pristine, values }) => {
formSubmitHandler = async () => {
await handleSubmit()
return values
}
return(
//... form components with the values prop passed into them below
//...i.e. <Part_1_Of_Form values={values}/>
If I understand correctly, you will note I destruct the render prop object in the JSX {({})} and get the values from the FormState.
I then pass them to various modular form components below - like <Part_1_Of_Form/> in order to make each part of the form react to state changes in other parts of the form. But my problem is I want it to react to more than the values. For example, if I want to display a label conditionally based on if another label option (or another option) is selected in another part of the form, I can't access it because I only get access to the values - not the labels.
Example, with a currency selection tool to propagate throughout the form using state:
<Field
name="part_one.currency"
component={MyRFFInputSelectComponent}
options={[{value: 'USD', label: '$ (USD)', symbol: '$'}, {value: 'EUR', label: '€ (EUR)', symbol: '€'}]}
required={true}
className="form-control">
</Field>
I can pass the value (let's say USD) around other parts of the form, using the render props and the values part of that returned object - but I don't want to. I want to pass the symbol - the value (USD) belongs to the database (it's only USD because the DB wants it as a string like that) - but the other parts of the form should display the symbol instead of the value once I select my currency in the top part of the form.
Example of what I have to do now elsewhere in the form:
<Field
...
append={values['part_one']['currency']}
Example of what I want to do:
<Field
...
append={symbols['part_one']['currency']}
Or maybe even better:
<Field
...
append={allFormData(notjustvalues)['part_one']['currency']['symbol']}
So that each input that needs a price can show a currency in the appended label.
Does this usecase make sense?
Is there another way to pick up the symbol or a way to add it to the FormState? I think its probably bad for perf to pass something like allFormData around just to get one custom symbol. I can't use the symbol for the value because my backend developer will cry. 😢
If I'm understanding you correctly, your value for part_one.currency needs to be the entire {value: 'USD', label: '$ (USD)', symbol: '$'} object.
Then you can do values.part_one.currency.symbol elsewhere in your form. If you only want the value to be 'USD' when you submit, you'll need to handle that in your onSubmit function. Does that help?

Ant Design: defaultValue of <DatePicker/> component is not working as expected

I am creating a detail page where I want to display an editable deadline and for that, I am using <DatePicker> component of Ant Design. The problem is when I set defaultValue={moment(deadline)} it's not showing the date deadline variable is holding but instead, it is showing the current date.
<DatePicker
showTime
format="YYYY-MM-DD HH:mm:ss"
placeholder="Set Deadline"
defaultValue={moment(deadline)} //moment(deadline) returns valid moment date objcect
onOk={(value, dateString) => {
newDeadline = value._d;
updateDeadline(newDeadline);
}}
/>
I don't know where I am doing wrong please help me to find it out...
UPDATE
When I console the value of deadline, typeof deadline, moment(deadline).toString() all are returning data as expected.
When I use value={moment(deadline)} instead of defaultValue={moment(deadline)}, It's also working fine.
One interesting thing, when I pass date string instead of deadline variable to defaultValue, It's working smoothly.

Categories

Resources