Category Archives: JavaScript

ReactNative – coloring text with a prop string

Update: While exploring further, I discovered that my issue was a lack of curly braces and not something more complex! Turns out you don’t need to do this whole thing with a new object, you can just use the var directly in a style parameter, as follows:

      <View style={{ flex: 1, flexDirection: 'row', backgroundColor:this.props.background }}>
        {this.props.children}
      </View>

Or even append it to an existing style:

<View style={[styles.CalcButton, {backgroundColor: this.props.background}]}>

I’ve been exploring ReactNative recently, as an alternative to using Unity3D to develop multi-platform apps for iOS/Android.

While I’m not a big fan of JavaScript, this framework seems to be worth the pain for non-graphic intense apps. I’ve been working through the tutorials and exploring the system myself for my own education. One thing that wasn’t obvious was how to set the color of a piece of text without adding an entry to the style-sheet.

I have a simple hello-world type component that renders a simple greeting with the passed name in props and I wanted to be able to add a color to the greeting, without adding a style-sheet entry.

Ideally I wanted something that looked like this:

<Greeting name="Colin" color="red"/>;

Acting on the name value is pretty trivial, but passing the color string and converting it to a style required some more google searching. I found similar questions and answers but nothing direct, so after a little experimentation, I got the following code to work:

class Greeting extends React.Component{
  render() {
    var colorStyle = Object.assign(
      {color : this.props.color}
    );
    return (
      <Text style={colorStyle}>
        Hello {this.props.name}!</Text>
    );
  }
}

This works by creating an object with a key:value pair of color and the color string passed. This style is then used in the Text object to set the color of the text.

This will work with a hex color too.

PHP and string addition

One of the problems of working on a website, is you’re constantly switching between Javascript and PHP.  Nothing worse than trying to track down an error to discover you’ve concatenated two strings in PHP thinking it was javascript…

$string1 + $string2 <> $string1 .  $string2

You’d think the $ in front of the variable names would have been a clue…

 

JavaScript page refresh timer

I wanted a web page I’ve been working on to auto-refresh, but not just after a certain time has elapsed, but when the clock is just past a quarter hour interval (i.e. x:15, x:30, x:45, x:00).

It’s pretty straightforward, but as I was searching around, it seems to be a pretty common question, so figured I’d put up my own answer here:

 function setAutoRefresh()
 {
   var interval = 15*60*1000; //every 15 mins...
   var timeNow = new Date().getTime();
   var nextInterval = (Math.floor(timeNow/interval)+1) * interval + 10000; //next time interval, plus 10 seconds...
   var nextIntDate = new Date();
   nextIntDate.setTime(nextInterval);
   console.log("Next timeout tick: " + nextIntDate.toLocaleTimeString());
   autoRefreshTimer = setTimeout(function(){
   console.log("Auto-refresh: " + new Date().toLocaleTimeString());
   reloadPage();
   },nextInterval - new Date().getTime());
 }

So we round up the current time in ms to the next 15 min interval, and add 10,000 so our event triggers 10 seconds after the interval (I have another process that ticks every 5 mins and updates the DB table this web page pulls from, so I wanted to make sure I got the latest data).

The var autoRefreshTimer is global and can be used to cancel the timeout timer when the page becomes hidden.

The var nextIntDate is only used for the console log, and can be removed if you don’t need that.

The function reloadPage resends all my ajax calls to reload the different data on the web page and then calls setAutoRefresh when it’s all done.

Hope that all makes sense.

 

Javascript, UTC datetime and formatting oh my…

I’ve been working on a project to display data stored in a MySQL database using the Google Graph API.  I’ve done this before, but this time I need to display the time the MySQL entry was created.  The DB row contains this information as a MySQL timestamp field, and is returned as a string when I fetch it, for example:

2017-07-09 02:30:00

This is in UTC, and as I’ve discovered, the PHP script has no idea of what timezone the browser is in, so either I need to pass that from JavaScript, or hand the UTC times back to the browser and let it take care of the conversion.  I decided it would be best to let the browser handle it (for now), and immediately discovered the confusion around formatting a Date string with JavaScript.

To me, this seems pretty basic, and I really don’t understand why it was omitted from the language.  There are a lot of libraries out there that will do this for you, but I ended up using jQuery, as I was already using it for the AJAX and graphing support.

jQuery provides the .datepicker class, which includes a date formatter.  I just needed the month and day, the month needs to be a short string, while the day is a number without any leading zeros.  I used the following:

$.datepicker.formatDate("M-d",utcTime)

Where utcTime is a Date object that’s been created from the MySQL string with:

var dt = new Date(Date.parse(item[0] + "Z"));

I append the Z to the MySQL string, so JavaScript knows its a UTC time.

At the time I did this, there is no option for handling Time within the standard jQuery package, so I added that manually, padding with a leading ‘0’ as needed, with the final date/time string being created with:

return $.datepicker.formatDate("M-d",utcTime) + " "
        + ("0" + utcTime.getHours()).slice(-2) + ":"
        + ("0" + utcTime.getMinutes()).slice(-2);

Note: I could have had .datepicker parse the string, but it wouldn’t have given me the time portion, so I do that in a separate step.