React not rendering child elements - javascript

I'm new to React, and I'm trying to bind React on my Angular Project. Currently I have some components which I need only bind children elements. But I am getting this error: Invariant Violation: GRID.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
My React code is here.
var GRID = React.createClass({
displayName: 'GRID',
render: function () {
var grid = this.props.grid;
var x = 5; //minutes interval
var timeSheet = []; // time array
var tt = 0; // start time
var ap = ['AM', 'PM']; // AM-PM
var options = [];
var key = 0;
//loop to increment the time and push results in array
for (var i = 0; tt < 24 * 60; i++) {
var hh = Math.floor(tt / 60); // getting hours of day in 0-24 format
var mm = (tt % 60); // getting minutes of the hour in 0-55 format
// timeSheet[i] = ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + ap[Math.floor(hh / 12)]; // pushing data in array in [00:00 - 12:00 AM/PM format]
tt = tt + x;
key += 1;
var time = {
"key": key,
"lable": ("0" + (hh % 12)).slice(-2) + ':' + ("0" + mm).slice(-2) + " " + ap[Math.floor(hh / 12)],
"value": ("0" + (hh)).slice(-2) + ':' + ("0" + mm).slice(-2)
}
timeSheet.push(time)
}
var select = React.createElement('select',
timeSheet.map(function (time, index) {
var option = React.createElement('option', { value: time.value, key: index, label: time.lable, className: 'md-option' });
return option;
})
)
return React.Children.map(select.props.children, (element, idx) => {
console.log(element);
return React.cloneElement(element, { ref: idx });
})
}
});
What is the problem with this code?

try to enclose your return statements inside a div tag.Else when your code will be converted into plain javascript and it will insert a semicolon at end of your return statement and hence leads to unreachable code.So enclose return in a
<div>
return //your code
</div>

Related

Expected identifier in array variable

I still need my function to work in internet explorer for compatibility reasons. The rest of the browsers support my array variable: var [sHour, sMinute, sSecond] but internet explorer does not. below is my full function.
function time_interval(start, end) {
var [sHour, sMinute, sSecond] = start.split(":");
var [eHour, eMinute, eSecond] = end.split(":");
var s = new Date();
s.setHours(sHour, sMinute, sSecond);
var e = new Date();
e.setHours(eHour, eMinute, eSecond);
var a;
if (s.getTime() < e.getTime()) {
a = e.getTime() - s.getTime();
} else {
e.setDate(e.getDate() + 1);
a = e.getTime() - s.getTime();
}
a = a / 1000;
var h = Math.floor(a / 3600);
var m = Math.floor((a % 3600) / 60);
var s = a % 60;
return (
(h ? h + ' hour ' : '') +
(m ? m + ' minute ' : '') +
(s ? s + ' second ' : '')
).trim();
}
const example = time_interval("10:00:00", "10:30:00");
console.log(example);
an example of the values taken by my array var is for instance, 10:30:00. This is why I added .split. How do I separate the arrays so that it is compatible and remove the Expected identifier error? I tried separating it in single variables but this does not work because of the split.
var sHour
var sMinute
var sSecond
Any help would be appreciated.
It's not the ideal solution, but you could just refactor your code like this:
var splitStart = start.split(":");
var sHour = splitStart[0];
var sMinute = splitStart[1];
var sSecond = splitStart[2];
You could also consider using a function and an object:
function convertTimeArrayToObject(arr) {
return {
hour: arr[0],
minute: arr[1],
second: arr[2]
}
}
var startObject = convertTimeArrayToObject(start.split(":"));
console.log(startObject.hour) // Will print the hour

Cannot read property 'length' error in JS

I have the an array of date range and I need to get a difference between number of days in between those months and create an array.
10/05/2015 - 11/05/2015 = 30 days
11/05/2015 - 12/ 05/2015 = 31 days
[30,31....]
I have the following code for date range.
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
dateRange(startOfLeaseDate, endOfLeaseDate);
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = stDate.clone();
var day = stDate.date();
while (now.isBefore(etDate)) {
//deal with variable month end days
var monthEnd = now.clone().endOf("month");
if (now.date() < day && day <= monthEnd.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
now = now.clone().add({
"months": 1
});
}
return dates;
}
function daysBetween(date1, date2) {
var Diff = Math.abs(date2.getTime() - date1.getTime());
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
function RunLedgerAndPV() {
var pDate = "11/21/2018"
var stDate = "10/5/2015";
var etDate = "12/4/2019";
var dateArr = createLedger(stDate, etDate);
var dayCounts = "";
for (var x = 0; x < dateArr.length; x++) {
dayCounts += daysBetween(dateArr[x], dateArr[x + 1], ",");
}
console.log(dayCounts);
}
RunLedgerAndPV();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
It's throwing an error at dateArr.length for some reason. Not sure what i am doing wrong here. Any help is appreciated. Thank you.
To add on to Vijay you are not returning anything in dateRange() either. Return dates array then return where you called dateRange().
Be aware this leads to more errors to do with your naming of daysBetween function when you are calling daysBetweenArrears.
EDIT
Few other errors:
You are calling getTime() on a string so this causes an error. You need to convert to a date object using new Date(date2) - new Date(date1).
Another return also missing for the Run function.
Code below:
function createLedger(stDate, etDate) {
if (stDate && etDate) {
var endOfLeaseDate = moment(etDate, "MM/DD/YYYY");
var startOfLeaseDate = moment(stDate, "MM/DD/YYYY");
return dateRange(startOfLeaseDate, endOfLeaseDate); // Added return
}
}
function dateRange(stDate, etDate) {
var dates = [];
var now = stDate.clone();
var day = stDate.date();
while (now.isBefore(etDate)) {
//deal with variable month end days
var monthEnd = now.clone().endOf("month");
if (now.date() < day && day <= monthEnd.date()) {
now.date(day);
}
dates.push(now.format("MM/DD/YYYY"));
now = now.clone().add({
"months": 1
});
}
return dates; // Added return
}
function daysBetween(date1, date2) {
var Diff = Math.abs(new Date(date2).getTime() - new Date(date1).getTime()); // Used new Date()
var TimeDifference = Math.round(Diff / (1000 * 3600 * 24));
return TimeDifference;
}
function RunLedgerAndPV() {
var pDate = "11/21/2018"
var stDate = "10/5/2015";
var etDate = "12/4/2019";
var dateArr = createLedger(stDate, etDate);
var dayCounts = "";
for (var x = 0; x < dateArr.length; x++) {
dayCounts += daysBetween(dateArr[x], dateArr[x + 1]) + ' '; // added a + ' ' to add a space to the result. Removed the ',' that you were adding in daysBetween but not using
}
return dayCounts; // Added return
}
RunLedgerAndPV(); //This wont show anything so wrap it in a console.log to see it return what you need
In your function "crrateLedger" you don't return anyting and you are assigning that in "var dateArr" hence it is set to undefined by javascript and you are trying to access property length of dateArr which is undefined

Calculate time difference and sum the difference using Javascript

i am trying to find the difference for end time and start time, followed by adding all the time difference
may i know how can i do so?
the code is as followed
function THcheck() {
var a, s, timeDiff, hr = 0;
var hdate, startTime, endTime, totalTime, timeDiff;
var output = "Date StartTime: EndTime: TimeDiff <br>";
var msg = "";
var DStime, DEtime;
var e = document.getElementsByTagName('input');
for (a = 0; e !== a; a++) {
if (e[a].type == "time" && e[a].name == "THStime[]") {
if (e[a].value && e[a].value !== "") {
startTime = e[a].value;
endTime = e[a + 1].value;
hdate = e[a - 1].value
alert(hdate + " " + startTime + " " + endTime);
timeDiff = endTime - startTime;
alert(timeDiff);
hr = parseInt(timeDiff.asHours());
alert(timeDiff);
totalTime += timeDiff;
alert(totalTime);
output += hdate + " " + startTime + " " + endTime + " " + timeDiff + "<br>";
if (hr >= 24) {
msg = "<br> Exceed 24 hrs! ";
}
}
}
}
alert(output + " Total time: " + totalTime + msg);
return true;
}
thanks in advance for your kind assistance and help on this!
I think you need to parse the hours first, converting from string to date and then convert the dates to milliseconds and use the milliseconds for the difference calculation. After this you convert the difference milliseconds into hours.
Here is some sample code which performs these steps:
const dateRegex = /(\d{2}):(\d{2})/;
function diffDatesInHours(d1Str, d2Str) {
const r1 = dateRegex.exec(d1Str);
const r2 = dateRegex.exec(d2Str);
if (!checkDate(r1)) {
console.log("First date format incorrect: " + d1Str);
return null;
}
if (!checkDate(r2)) {
console.log("Second date format incorrect: " + d2Str);
return null;
}
const d1 = createDateFrom(r1);
const d2 = createDateFrom(r2);
const diff = d1.getTime() - d2.getTime();
return Math.abs(diff) / (1000 * 60 * 60);
}
function checkDate(r) {
if (r === null) {
return null;
}
return r.length > 0;
}
function createDateFrom(r) {
let date = new Date();
date.setHours(r[1], r[2]);
return date;
}
console.log(diffDatesInHours("09:30", "21:00"));
console.log(diffDatesInHours("09:30", "21:"));

Javascript timer countdown in Mozilla and IE - works in Chrome

The Javascript below is used to format a range of timers for my php game. When a user submits an option it then resets the timer saying "Ready" to count down 1 minute based on the time logged when the user submitted against the current time. When the timer reaches '0' it then resets to default of "Ready". It's working perfect with CHrome however Firefox and IE it only displays Ready but will not update the timer and begin counting down. Any help is deeply appreciated.
var d = new Date();
var tarray = new Array();
function loadTimers()
{
var timersrow = g('timersrow');
var html = '';
var list = tinfo.split('|');
var i;
var cell
for ( i=0; i<list.length; i++ ) {
data = list[i].split(',');
cell = ce('td');
cell.innerHTML = data[0];
timersrow.appendChild(cell);
//html += '<td id="tcell' + data[0] + '">' + data[0] + '</td>';
tarray[tarray.length] = new objTimer(data[0], data[1], cell);
}
//timersrow.innerHTML = html;
updateTimers();
}
function updateTimers() {
var i;
for ( i=0; i<tarray.length; i++ ) {
tarray[i].update();
}
setTimeout('updateTimers();', 250);
}
function objTimer(label, time, cell)
{
this.label = label;
this.time = Date.parse(time);
this.cell = cell;
function update()
{
var t = new Date();
var val = this.time - t.getTime();
if ( val > 0 ) {
this.cell.innerHTML = 'Next ' + this.label + ': ' + formatSeconds(val);
} else {
this.cell.innerHTML = 'Next ' + this.label + ': Ready';
}
}
this.update = update;
}
function formatSeconds(seconds)
{
var h = 0, m = 0,
seconds = parseInt(seconds / 1000);
if (seconds > 60 * 60 ) {
h = parseInt(seconds / (60 * 60));
seconds -= h * 60 * 60;
}
if ( h < 10 ) {
h = '0' + h;
}
if ( seconds > 60 ) {
m = parseInt(seconds / 60);
seconds -= m * 60;
}
if ( m < 10 ) {
m = '0' + m;
}
if ( seconds < 10 ) {
seconds = '0' + seconds;
}
return h + ':' + m + ':' + seconds;
}
loadTimers();
Thanks all for your help. I have resolved the issue as I believe having functions called before they are defined was one of the key issues and changing the rounding system to math.floor instead of parseInt.
Also silly me - Var cell had no ';' which may have been the biggest reason.

jQuery javascript clock with settable time?

I am looking for a simple jQuery clock.
There are tonnes out there, but I am looking for one where I can set the current time, and the output format.
So I want to be able to call something like
$('#clock').clock({
format: 'l dS F Y, h:i a', //PHP date format, but anything that can mimic this output is good
date: '2012-07-01 23:59:59' //MYSQL date format, but can output as anything
});
Is there something like this (even raw js will do).
Creating a counter for a clock is pretty simple, you can probably write one in less time that it takes to review the answers you'll get here. Below is one I made as an example of prototype inheritance.
Just format the output however you like, add CSS to your hearts content to make it look good.
// Create a digital clock
// Write time in hh:mm:ss.nnn format
// el is an element
function Clock(el) {
if (typeof el == 'string') el = document.getElementById(el);
this.el = el;
}
// Clock methods
Clock.prototype = {
// Utilty functions
addZ: function(n) {
return n < 10? '0' + n : '' + n;
},
addZZ: function(n) {
return n < 10? '00' + n : n < 100? '0' + n : '' + n;
},
formatTime: function(d) {
return this.addZ(d.getHours()) +
':' + this.addZ(d.getMinutes()) +
':' + this.addZ(d.getSeconds()) +
// Milliseconds are just for debug, remove from finished version
'.' + this.addZZ(d.getMilliseconds())
},
update: function() {
var clock = this;
var d = new Date();
// Set next run to just after full second
var interval = 1020 - d.getMilliseconds()
this.el.innerHTML = this.formatTime(d);
setTimeout(function(){
clock.update();
}
,interval);
}
};
// Create a new clock
// el is id or element to display text in
function newClock(el) {
var y = new Clock(el);
y.update();
}
Edit
A generic date format function: http://blog.stevenlevithan.com/archives/date-time-format
A specific function to format a date to be like Tuesday 05th July 2011, 10:31 am:
var formatDate = (function() {
// Days of the week, zero is Sunday
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
// Months of the year, zero is January
var months = ['January','February','March','April',
'May','June','July','August','September',
'October','November','December'];
// Format single digit numbers
function addZ(n) {
return n<10? '0' + n : '' + n;
}
// Add ordinal to numbers
function addOrdinal(n) {
return ['th','st','nd','rd'][(''+n).slice(-1)] || 'th';
}
return function (date) {
var d = addZ(date.getDate());
var h = date.getHours();
var ap = h < 12? 'am' : 'pm';
h = addZ(h > 12? h - 12 : h);
return days[date.getDay()] + ' '
+ d + addOrdinal(d) + ' '
+ months[date.getMonth()] + ' '
+ date.getFullYear() + ', '
+ h + ':'
+ addZ(date.getMinutes()) + ' '
+ ap
}
}());

Categories