Is there any alternative for state in class component of react native? - datepicker

i have a dynamic form that contains multiple date fields. i don't know how many date fields will be there in future. if i select one date from date picker it shows in all fields the same date as shown in the picture.
i don't want to use state because i don't know the exact number of date fields in my form in future as it is dynamic. is there any alternative for state or any solution for it with state?
in the given picture i used state just to show the issue, now i want to use something by which can get date from multiple fields
like this here second field picked the same date of first field
if (item.element == "DatePicker") {
let i_id = item.id;
return (
<View style={styles.input}>
<View style={styles.layout}>
<Text>{item.label}</Text>
<Text>{this.state.cdate}</Text>
<Button title="Date" onPress={showDatePicker} />
<DateTimePickerModal
isVisible={this.state.setDatePickerVisibility}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</View>
</View>
);
}
const showDatePicker = () => {
this.setState({
setDatePickerVisibility: true,
});
};
const hideDatePicker = () => {
this.setState({
setDatePickerVisibility: false,
});
};
const handleConfirm = (date) => {
Moment.locale('en');
let dates = Moment(date).format('DD-MM-YYYY')
this.setState({
cdate: dates,});
hideDatePicker();
};

Related

Material UI date picker Date format React

I can't see to format the Material UI Date picker in a React app??
When a user selects a date, I want it to format to be MM/DD/YYYY. I looked up a couple answers but it's not clear where the function to change the format is supposed to go??? For some reason, there is no clear function/location of where it goes online>>
DatePicker component
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* `DatePicker` can be implemented as a controlled input,
* where `value` is handled by state in the parent component.
*/
export default class DateSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
controlledDate: null,
openSnackbar: false,
snackbarText: {
dateconf: 'Date has been entered!'
}
};
}
formatDate(date){
return (date.getMonth() + 1) + "/" + date.getFullYear() + "/" + date.getDate();
}
handleChange = (event, date) => {
console.log('we are in a handle change in date select', event, date)
this.setState({
controlledDate: date,
});
// this.setState({
// openSnackbar: true
// })
};
render() {
console.log('state and props in date select', this.state, this.props)
return (
<DatePicker formatDate={this.formatDate}
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
);
}
}
///THE PARENT COMPONENT
handleDatePicker = (name, date) => {
console.log('handling date change', name, date)
this.setState(prevState => ({
currentRow: {
...prevState.currentRow,
purchase_date: date
},
purchase_date: date,
actionType: 'date'
}))
this.setState({
openSnackbar: true
})
}
<DateSelect
hintText="Purchase date"
value = {this.state.purchase_date}
onChange={this.handleDatePicker}
/>
You need to use formatDate function to format the date and time in date picker
formatDate --> This function is called to format the date displayed in the input field, and should return a string. By default
if no locale and DateTimeFormat is provided date objects are formatted
to ISO 8601 YYYY-MM-DD.
<DatePicker
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
formatDate={(date) => moment(new Date()).format('MM-DD-YYYY')}
/>
if you do not pass any format on the date it seems that the min and max date are not working.
For more details material-ui/DatePicker
Straight from the documentation of DatePicker. Try this
<DatePicker
inputFormat="MM/dd/yyyy"
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
inputFormat should usually do the trick. You can change it around the way you want and it can be used for dateTimePicker as well.
For example,
inputFormat="yyyy/MM/dd"
or any other way
formatDate did not work for me in V4. documention suggest inputFormat and worked properly.I found usage example here
<DatePicker
openTo="year"
views={["year", "month", "day"]}
value={toDate}
onChange={(newValue) => {setToDate(newValue);}}
maxDate={maxdate}
minDate={minDate}
format="DD-MM-YYYY"
/>

DatePicker date input with custom format

I want to stote dates in my state using redux-form. I use react-datepicker. To make the datepicker compatible with my redux-form i write:
import React, { PropTypes } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
const MyDatePicker = ({ input, meta: { touched, error } }) => (
<div>
<DatePicker
{...input} dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
The problem is that when i choose date i want it to show as DD-MM-YYYY but i want the date to be saved in my state with the YYYY-MM-DD HH:MM:SS format. How to do this? I use the moment's format function but it did not seem to work
You should use the value lifecycle methods that redux-form provides for this.
Use parse to format the value coming from react-datepicker for storage and format to parse the value from the store back for react-datepicker to present it. Example:
function formatDateForInput(storedDate) {
// the returned value will be available as `input.value`
return moment(pickedDate).format('right format for your input')
}
function parseDateForStore(pickedDate) {
// the returned value will be stored in the redux store
return moment(storedDate).format('desired format for storage')
}
<Field
component={ MyDatePicker }
format={ formatDateForInput }
parse={ parseDateForStore }
/>
If this does not work for your, I would recommend checking if you need to put a custom onChange handler between the DatePicker and input prop provided by redux-form. Because it could be that the values DatePicker is using to call onChange are ones that redux-form does not understand. Like this:
const MyDatePicker = ({ input, meta: { touched, error } }) => {
const onChange = event => {
const pickedDate = event.path.to.value;
input.onChange(pickedDate);
}
return (
<div>
<DatePicker
dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
onChange={ onChange }
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
}
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
Hope this helps!
If i am understanding correct you just need 2 different formats for same date one on UI and other to save ? moment(date).format('DD-MM-YYYY') and moment(date).format('YYYY-MM-DD HH:MM:SS') will give you both formats date.
Just use the prop dateFormat="dd/MM/yyyy"
Example :
<DatePicker
selected={startDate}
onChange={date => handleChange(date)}
dateFormat="DD/MM/YYYY"
/>
I used the below props -mask, inputFormat and format - to change the default format to "yyyy-MM-dd" format.
The format code "yyyy-MM-dd" is important, play around this to find the desired format.
Example:
<LocalizationProvider dateAdapter={AdapterDateFns} >
<DatePicker
label="SomeDate"
{...register("details_received_date")}
mask="____-__-__"
inputFormat="yyyy-MM-dd"
format="yyyy-MM-dd"
value={someDate}
onChange={(newValue) => {setSomeDate(newValue);}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
This will display in the front end and provide the value as well in the desired format.
Hope this helps.
Try this
inputFormat="DD/MM/YYYY"
const [value, setValue] = useState(null);
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="DatePicker Example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
inputFormat="DD/MM/YYYY"
/>
</LocalizationProvider>

Select all checkbox redux form

I want to check/ uncheck all checkboxes the moment I select Check All but can't make it work. I'm using material-ui components and redux-form. my plan is to grab checkAll field value using formValueSelector API and set checkbox A and B value based of that. Also tried using value prop but no luck still.
import React from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { Checkbox } from 'redux-form-material-ui';
let Form = (props) => {
return (
<form>
<Field name="checkAll" id="checkAll" label="Check All" component={ Checkbox } />
<Field name="a" label="A" component={ Checkbox } checked={ props.checkAll } />
<Field name="b" label="B" component={ Checkbox } checked={ props.checkAll } />
</form>
);
};
Form = reduxForm({
form: 'Form'
})(AddReturnModal);
// Decorate with connect to read form values
const selector = formValueSelector('Form'); // <-- same as form name
Form = connect(
(state) => {
const checkAll = selector(state, 'checkAll');
return {
checkAll
};
}
)(Form);
export default Form;
You could use change method. From docs:
change(field:String, value:any) : Function
Changes the value of a field in the Redux store. This is a bound action creator, so it returns nothing.
The only solution I see is to loop over the list of checkboxes and call change(checkboxName, value) on them.
#notgiorgi is right, to select all checkboxes, you can do this:
selectAll = () => {
const { change } = this.props
['a', 'b'].forEach((field) => change(field, true))
}
If you wanted a toggle, you might easily/cheaply/ignorantly be able to keep a rough reference to the selectAll state:
selectAllValue = false
selectAll = () => {
const { change } = this.props
['a', 'b'].forEach((field) => change(field, this.selectAllValue))
// toggle select all to select none
this.selectAllValue = !this.selectAllValue
}

Date from input field not being stored

I set up my Angular-Meteor application to allow users editing their date of birth. I am using bootstrap3-datepicker on the input field.
The input field in the form is defined like this:
<div class="form-group">
<label for="dateOfBirth" class="control-label">Date of Birth:</label>
<input type="date" id="dateOfBirth" class="form-control" ng-model="profileEdit.profile.dateOfBirth"/>
</div>
Picking and displaying the date works fine in the front-end, but the date is not stored when I save my form (all other data is). If a date exists before editing the record with the form, the date gets lost.
This is my controller:
class ProfileEdit {
constructor($stateParams, $scope, $reactive) {
'ngInject';
this.profile = Meteor.user().profile;
$('#dateOfBirth').datepicker({
format: "dd.mm.yyyy",
weekStart: 1,
startDate: "01.01.1940",
startView: 2
});
}
save() {
var profile = {
firstName: this.profile.firstName,
lastName: this.profile.lastName,
gender: this.profile.gender,
dateOfBirth: this.profile.dateOfBirth,
level: this.profile.level,
description: this.profile.description
}
Meteor.call('users.profile.update', profile, function(error, result) {
if(error){
console.log("error", error);
}
if(result) {
console.log('Changes saved!');
profile = {}
}
});
}
}
Logging profileEdit.profile.dateOfBirth to the console before saving the form data yields undefined.
It appears to me I am already losing the date between the form and my save() method. Why could this be?
I had the same issue with another datepicker, it appears that when a third party plugin updates the DOM, it does not update the modal that is attached to it. What I had to do was use the datepicker's events to catch the change and programatically update the field, IE:
$('.datepicker').datepicker()
.on('changeDate', function(e) {
// update your model here, e.date should have what you need
});
http://bootstrap-datepicker.readthedocs.io/en/latest/events.html

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});