Why I Love React 16

Fragments are the feature I intuitively expected in React 15.

They are a really welcome addition to React 16.

This is now valid:

{wantingToResume && [<hr/>, <ResubscriptionContainer />]}

Notice that the horizontal rule, and a full component are being returned inside an array.

The official announce post has another example.

I love React. Thank you to everyone involved in getting this new release out of the door, and thank you to everyone in the React community for making my time with the front end a heck of a lot more enjoyable than it used to be.

PHP > React > Server Side Rendering > PHP

Back when I was a server room techy there was a line my old boss used to say whenever I got wind of something new and shiny:

There are no new ideas in IT, just the same ones on repeat.

Of course he was being tongue-in-cheek, but there was a truth in what he said.

For example, around the time I was in this role, the IT industry was moving from distributed to centralised. That is to say we had a bunch of servers dotted all over the county, and the plan was to bring them into just two central server rooms.

This, I was assured, was very much like “the olden days” when individual desktops were replaced with “dumb terminals”, which relied heavily on a centralised Mainframe.

At some point, someone (likely an army of well paid consultants) espoused the failings of such an architecture (oh my, single point of failure!) and likely sold them a bunch of high powered standalone desktops.

This worked well for a while, then companies like Citrix came along and sold a different spin on “dumb terminals” using your existing high powered desktop, and so on, and so on.

What the heck does any of this have to do with Web Development, I hear you ask.

Good question.

As you may recall, I have been getting quite excited about launching the new, shiny revision of CodeReviewVideos.com. I had my zip lock baggy of party poppers at the ready. Things were looking super.

Then, over the previous weekend, it dawned on me:

How’s the SEO on this new site then?

Seeing as about 70% of the incoming visitors to CodeReviewVideos arrive via Google, I figured I should probably – ya’ know – give this some consideration.

I checked, and it turned out that I had, ahem, neglected to set any of the head information.

Yes, I felt quite the chimp.

But not to worry, I have all the SEO data just sat ready and waiting in the DB. After all, it’s exactly the same as for the existing site.

What happens with the existing site is what happens with pretty much any PHP site I have ever worked with:

  • A request comes in
  • The relevant data is fetched from the DB (thanks, Doctrine)
  • This data populates a template (thanks, Twig)
  • The response is returned to the end user (thanks, Symfony!)

It doesn’t matter if the request is from Google Bot, or from a real person. The process is always the same.

What this means is that the response contains everything needed to make a full page representation.

Google Bot can look at the page and see all the expected “stuff”: the header tags, and body content, it’s all there.

Sure, we can then augment this with a snazzy bit of JS here and there, but largely, it’s good to go.

Web 2 Point… Oh?!

Then sometime a few years back, Single Page Applications (SPA, and not the relaxing kind) became popular.

SPA – not as relaxing as you may have been led to believe

Fast forward a few years and boom, I’ve done a few of these here SPA’s with React and Angular, and I’m thinking: yeah, this is awesome, let’s make CodeReviewVideos all snazzy using all this wicked tech.

So I did.

The new version of the site uses React, and Redux, and Redux Saga, and it talks to a Symfony JSON API, and it’s all lovingly tested and fills me with warm fuzzy feels whenever I work with either code base.

Unfortunately, all this awesomeness does make the architecture more complex. Let’s revisit how a request / response works now:

  • A request comes in
  • The user gets sent this:
<!DOCTYPE html><html lang="en"><head><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"><title>Code Review Videos</title><script type="text/javascript" src="https://js.stripe.com/v2/"></script><link rel="shortcut icon" href="/favicon.ico"><link href="/main.0c31c168e455a7de8ecee02d7d21798e.css" rel="stylesheet"></head><body><div id="app"></div><script type="text/javascript" src="/main.bf614c9bf38e83f9d4e0.js"></script></body></html>
  • We are done, let’s go to the pub.

If you’re a bot Yahoo, Bing, or Yandex, you’re now done.

Forgetaboutit

By all accounts these bots do not process JavaScript, so forgettaboutit.

This may very well be of no major consequence.

By way of some hard figures, the combined total visitors that CodeReviewVideos received over the last 7 days that came via a search engine that isn’t Google was:

11.

Fixing the world for the sake of these other search engines probably isn’t worth my time right now.

But Google… well, we must do better.

Now, it turns out that maybe Google has already solved this problem.

My guess is they have. I mean, this is Google. They are super smart, and it’s their job to get this right.

But can I risk killing the site on a maybe.

No, definitely not.

What Happens Next?

Back to the HTML from above. Thinking about the request / response sequence, what happens next?

Well, on the client side – which is to say in your visitor’s browser – assuming they have JavaScript enabled, the JS is read and run (or parsed and executed, if you’re a CS text book).

Cus i’m Shiny!

This is where all the cool stuff happens!

  • React builds the page from my components
  • The components instruct the browser to make requests to the back-end API for the real content
  • The real content is received
  • React renders the content into the right place(s)
  • The visitor is completely indifferent

By the way, if the visitor doesn’t have JavaScript enabled then they are going to have a bad time. But, ya know, 2017, etc, etc.

When I realised my mistake about SEO last weekend, my first thought was to simply grab my Helmet and populate the head tags using the API response.

Alas, as we have now seen, this simply will not do.

So I figured I would be a Smart Guy ™ and put a caching layer in front of my web server. Maybe I could trick the bots by returning a fully cached version of each page.

Yeah, that didn’t work.

At this point I had a short breakdown.

Fortunately, PHP North West happened which took my mind off of the problem.

Ultimately though, it meant I had to postpone the scheduled launch. And that sucks.

Server Side Rendering anybody? No? SSR? No?

Of course I’m not the first person to have experienced this problem.

There is already a solution:

Server Side Rendering.

The idea here is rather convoluted, but stick with me:

We already have our shiny new React site, right? Yes, yes we do.

Server-side-rendiamous!

So, let’s get a Node JS instance to sit in front of our React site, and uses some of the stuff we learned in the Dark Arts class at Hogwarts to run this code, then convert the response to a string, and write the string to a template, which is turned into another string which is sent back to the browser so that we now have the necessary HTML to please Google like in the olden days.

Oh my.

It seems like we’re repeating ourselves here.

But now with more layers. More bug filled, confusing, maybe unnecessary layers.

Anyway, that’s where I’m at with CodeReviewVideos right now. Trying to migrate my existing front end code from client-side only, to this SSR setup to essentially reproduce the outcome I already have with plain old PHP.

What this means is right now I have no ETA on the next version, and once it is again “ready”, I will need to go back through a phase of testing before go-live.

Video Update

This week saw three new videos added to the site:

#1 – [Part 1] – Twig Extensions – How to add a custom CSS class to an invalid form field

Between this, and the next video we look at a question I got asked late last week:

How can I add a custom CSS class to the `input` / other form field when validation fails for that field?

This video explores one possible solution to this problem.

What happens however, is that we end up with a bunch of repeated logic living in a Twig template.

Generally, if you find yourself repeating yourself… or you end up with complex logic living inside a Twig template, you can probably extract it into a better location – a custom Twig function.

#2 – [Part 2] – Twig Extensions – Create a Twig Extension Function to Keep DRY

As such we look at extracting this repeated logic from our Twig template into a Twig Extension.

It’s one of those topics that sounds like it might be hard, or too nerdy, or whatever.

It’s just a strange name for a very useful concept.

If you use Twig in any seriousness, and you don’t yet know about Twig Extensions then this video should help you understand how to use one, and why it’s not as hard as you might think to do so.

#3 – Docker Elixir Phoenix – Part 1 – The Web Server

In my personal experience there has been no better way to improve my overall knowledge of software development than by learning another language.

Elixir, in this case, is the language.

Phoenix is somewhat akin to Symfony, or Rails, or what have you. It’s a framework for web applications.

In this series we are building up a small but functional (ho, ho) JSON API using Elixir and Phoenix.

In this video we cover how to set up the Web server by way of docker-compose.yml. This series is a little more advanced than most of the content on CodeReviewVideos, but I hope you’re finding it enjoyable all the same.

That’s It, That’s All

That’s just about it from me this week.

My favourite snowboarding movie 🙂 Great soundtrack.

As mentioned last week I spent the previous weekend at the PHP North West conference.

You can read about my time there right here.

There are pictures 🙂 and also a lesser spotted Rasmus found in his natural habitat.

Have a great weekend, and happy coding.

Chris

Here’s How I Learn – The Two And Ten Method

I had an interesting discussion this week with a developer who is currently working mainly with WordPress websites, and wanted to know how get started with “the new stuff”.

The new stuff this developer was referring too would be things like React, VueJS, maybe Angular, but more generally JavaScript’s ES6 (and beyond), and things of that nature.

It’s a good question, and one I have been thinking about ever since.

As you may recall from previous emails / blog posts, I spent quite a while over the past few months working on a WordPress plugin myself. As it turns out, that plugin is now very unlikely to ever get released. That’s sadly very unfortunate, but there’s no point dwelling on that.

One of the cool things I tried with that plugin was to use React inside WordPress. It worked quite well, certainly better than I expected.

Why I mention this is because if you really want to get stuck in to using React (or other libraries), you can do so, even if you are working in the confines of another project (WordPress, Drupal, Magento, etc).

Ok, but maybe this is not so helpful. I was working on a plugin of my own creation, with no boss and/or client to satisfy. This allowed me to satisfy my own curiosity (can I even do this?) at the expense of a few days of prototyping and experimentation.

Typically that’s not how most paid software development goes.

Let’s change this up then, and view the problem from the perspective of a developer working in one of the many, many “full service agencies” we have here in the UK. Typically these agency businesses cover a wide range of activities:

  • Social Media management
  • Pay Per Click advertising
  • Logos and branding
  • Search engine optimisation
  • Web development

I’m going to generalise here and say that the vast majority of the web development projects these companies undertake involve WordPress, the lovable blog platform that’s also a shop, a membership site, a boat, a car, and whatever else its been hacked into these days.

The problem we hit upon here is that if your day job is to churn out WordPress website after WordPress website, there is an imposed ceiling on your learning. By which I mean that whilst initially the problems you will be tasked with will feel challenging, after you’re on your 10th build, adding yet another jQuery slider is going to be very run-of-the-mill.

And this becomes a major problem.

Firstly – jQuery. WordPress is full of jQuery, and whilst it is a really useful library that’s good to know, and to be able to use, it’s not going to set your CV on fire.

Secondly – WordPress. It gets a(n unfair) ripping even from the PHP community. When used for the right things, WordPress can be a great platform. However, without an experienced mentor to guide you, it’s incredibly easy to write sloppy / confusing / pain-inducing code.

Put together, these two skills can likely see you through for the next 3-5 years without any issue. If you have no desire to improve further than being yet another commodity developer taking up a seat in an agency then feel free to stop reading here.

Still reading?

Good.

The question now becomes:

How do I get from my day job doing WordPress, to coding in React / modern JavaScript?

This Is The Modern Way

I’m going to let you in on a little secret:

Your boss doesn’t want you to improve.

If you improve too much you will either want promotion, or worse, you will leave and take your skills elsewhere.

Either way, your current employer loses out.

Of course, your employer wants you to improve a little. They don’t want you spending a day trying to get that jQuery slider to work. They would rather it took you twenty minutes so you can get on to adding another jQuery slider to your next project.

As a side note here this isn’t something that’s unique to software developers / agencies. I have seen this pattern repeat in every company I’ve worked with.

I used to work with a lad who would sit and moan about how the organisation never trained him. He wanted to become a senior member of the team – if only the pesky business would pay for him to go on a week-long training course. I remember him sitting and moaning about this for years (I worked there for 9 years), all the while his more pro-active peers steadily climbed the corporate ladder around him.

Here’s the thing though:

A week long training course won’t really help you.

An exam certificate won’t help much either.

All that matters is experience.

And the best way to get experience is to take control of your own learning.

Now here’s the really cool part:

You can learn whatever you like.

You don’t need to wait for a project to come along in your day job to start hacking on React. In all likelihood that day will never come, anyway.

What about other cool technologies you’ve heard about? Docker, for example. Will your boss ever come over to your desk and say, hey, let’s try using Docker for this project!

Of course not. The chances are your boss hasn’t even heard of Docker.

You know who has heard of React, and Docker? The team at your next job.

Ok, so here’s my approach which I call two-and-ten:

#1 – Get On The Jobs Boards

Don’t be a newb and browse jobs boards at your work PC.

Instead, browse either on your phone (at dinner time) or at home.

Search for skills you would like to learn, and see what you could potentially earn if you had experience in this skill.

What I would suggest is looking for both permanent, and contract roles, and assess the pay.

There’s no point devoting a bunch of time (potentially years) to learning something that doesn’t pay that well. I know, I know, do what you love, and all that, but if you have a choice between tech A and tech B, and tech B pays £xx,xxx more per year, why would you learn tech A?

What you will find in doing this exercise is that there’s a bunch of related skills that frequently come up on the job’s listings for any particular skill set. For example, if you look for Docker roles, you will likely frequently see requests for experience in Amazon’s AWS, Puppet, Ansible, and more.

Spend some time here. This will form the core of the skills you will be learning.

Write these skills down, along with the pay rates. This will be a strong motivator to keep learning, when you inevitably hit the tough spots.

#2 – The 10 Step Plan

It may be that you really want to learn React.

Well, the good news is that we’re still early in the curve. Even if it takes you a year to gain proficiency, there will likely be more jobs then than now.

Take this into consideration when choosing what you are learning. Try not to back the 3-legged horse 🙂

Once you know what it is you want to learn (e.g. React) then what I do next is plan out 10 small projects that take me from “what the heck is this?” to “ok, I have some idea how to do this!”.

Here’s how I would break down learning React:

1. Read through, and follow along with the official Facebook tutorial.

This will give you the basic knowledge of what React is, and what it can do for you.

2. Try Create React App

This is pretty much the defacto way to kick start a React project these days, and means you completely avoid having to learn about Webpack, or Babel.

3. Make a Very Simple One Page Web App

Using the skills you learned in the previous step, now try to create a one page website / web app with a HTML table and some fake data.

At this point you can still easily Google for answers, but without a written tutorial to guide you, you have to start thinking for yourself. It’s hard, and it may take you a few evenings of work, but now you’re learning.

4. Make a Multi Page Web App

You now know how to make a one page web app. What about if we need more than a single page? How to do we navigate between these pages?

Each page doesn’t need to do anything interesting at this point. It’s just about pushing ourselves further.

Try to do this without using a third party library.

5. Make a Simple Form

Forms are almost unavoidable in a modern web app. Sooner or later you will need to accept user data.

Add a single text input , along with a submit button. When data is submitted, have it log out to your browser’s developer console.

6. Make a More Complex Form

There’s more to forms that text inputs, unfortunately.

Practice adding a dropdown select  box, and for extra points, make the list of options dynamic.

At this point you may wish to try my Symfony 3 with ReactJS and Angular course. You can skip the Angular part without any issue.

7. Get data from an API

We have no database setup. We could get stuck here and start worrying about how to set up a back end, what language that should be in, how it would even work…

But we don’t need to do any of this. Set up a fake REST API using the JSON Server library.

Then, use React to GET  data from that API.

This is a super common thing you will be doing with React, so it pays to learn how to do this.

True story: I have been in interview situations where I have been expected to write a CRUD-style app in this fashion.

8. Update An API

Most of the time you won’t just be reading (GET ) from an API. You will need to add new, or update existing data, too.

Good news, we can use everything we learned in #7, and expand on our knowledge here.

9. Talk To A Real API

It’s cool hitting the JSON Server from #7, and #8, but this cannot replace working with a real life API.

Fortunately there are tons of publicly available APIs for us to play with.

Find one that seems interesting and code up a search box to send in queries, and another page to display the results.

For extra credit, choose an API that requires authentication. Feel free to use a third party library here, as it’s very unlikely you’d write this part by yourself in real life.

10. Go Crazy

You surely can’t be around React for too long without hearing about Redux, Reselect, Redux Saga, React Router, MobX, Redux Form, React Drag and Drop, and who knows how many more.

You’re now at a point where tackling my React, Redux, and Redux Saga With Symfony 3 suddenly isn’t so daunting.

There’s still a lot left to learn, but now you know the basics and can start building up your knowledge further.

The good news here is that you’re further than most people who say they want to learn React will ever get.

I use this same process over and over, every time I want to learn something new. Start simple and take baby steps. Just because they are baby steps doesn’t mean you won’t stumble and fall – watch how many times a toddler falls on their backsides before they finally master taking just a few short steps.

It’s easy to forget how important it is to be persistent. 

The key thing here is we are no longer reliant on our boss / day-job to structure what it is that we learn.

We get to work on cool and interesting things (such as React, and ES6 / ES2017) at our own pace, and without pressures of “when’s it done!?”.

Each of these steps can be tackled in small bursts.

I completely understand that after a day of working on WordPress you may have no desire to get back on a computer. That’s fine. You don’t need to do this every single evening.

The idea behind this approach is to have small goals which are well defined, and don’t need the full spit-and-polish of a production implementation. They can be super rough, no tests, just fun and perfect for self-improvement.

Video Update

This week saw three new videos added to the site in new short series:

Testing DateTime In PHP

We know we should be testing our applications, but sometimes testing is really hard. One such time is when we need to test instances of PHP’s \DateTime, or more recently, \DateTimeImmutable.

The primary problem with dates and times is that they constantly and unceasingly march ever forwards.

This presents a huge problem in our tests, where we need predictability.

In this series we cover three ways to address this problem.

Until next week, have a great weekend, and happy coding.

 

Chris

10 Tips For Better Symfony Debug Logs with Monolog 

I can’t quite believe it’s over a month already since Christmas day. Although I only need to step outside for a few moments to wish it was Summer already. I’m much happier coding in my shorts and t-shirt.

A number of people have asked for a suggested watching order / learning track, and with 50 courses to choose from, I can totally understand it can be hard knowing where to start. With this in mind, I’ve added a Learning Tracks page to the site.

This week saw three new videos added to the site.

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest-happy-path

Firstly we cover testing JavaScript’s Fetch, the nicer replacement to XMLHttpRequest. It baffles me why XML is uppercase, but Http is title cased. Anyway, fetch is nice to use, but testing can still be a little tricky.

To begin with, we cover the happy path, which gets our setup code out of the way. Seeing how things work when the everything is right in the world is a great way to start. But of course, once real users start tinkering with our systems, inevitably they will find new and baffling ways to destroy our good intentions. Which is why…

https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest-unhappy-paths

We also need to cover the “unhappy paths”. And in this case, testing that our code throws the expected exceptions is a little trickier than you might expect. It’s one of those problems that you might estimate at taking you a morning, but end up losing two days too – never fun explaining that in the daily stand up.

Fortunately help is at hand, and we will use a small snippet of code to ensure testing when things go wrong is that much easier.

When it comes to tracking down errors, of course it’s not just the client side that can go wrong. If you’ve worked with Symfony beyond the most basic of applications then more than likely you will have needed to log out additional information to help you debug. Monolog is the fantastic out-of-the-box logging solution in Symfony, and so…

https://codereviewvideos.com/course/log-log-it-s-better-than-bad-it-s-good/video/10-tips-for-a-better-symfony-debug-log 

In this video we look at 10 ways to improve your Symfony debug log output by making use of a variety of options and techniques that Monolog gives to us.

We start off with the basics here, but quickly cover the handler stack – including the rather brilliantly named fingers_crossed  handler, which you will have seen in config_prod.yml  – then onto channels, logging from console commands, and also how to log out to Graylog.

This video will be free to watch until next Friday, so be sure to set aside 10 minutes for this one.

Lastly, did you know you can keep track of the latest videos via an RSS reader? I have a full feed available to ensure you never miss a video.

Until next week, take care, and happy coding.

Chris

An issue with React Widgets DateTimePicker

When you have the fix to a problem, but don’t know the root cause of why that problem is happening, you have two choices:

  1. Accept you have a solution, and move on, or;
  2. Accept you have a solution, and figure out the cause of the problem.

The problem is, #2 takes time. And that might not be time you have currently.

Dwelling on some problems is not the best use of my time in my current position.

So here’s my problem, and a solution, but I cannot offer you the root cause to this problem. Nor is it the defacto solution, I believe.

Using React Widgets DateTimePicker

I guess you’re either the kind of developer who creates everything themselves.

Or you first try using other people’s.

I wanted a Date Picker, ideally with time, and I would like it to be hooked up to Redux Form.

The good news, Redux Form already works nicely with React Widgets. See the previous link for a decent tutorial. And this code sample.

As a result, I can quite easily add in a Date Time Picker that’s hooked up to my Redux Store. This is good. It pleases me.

It also allows me to start laser focusing my A/B tests.

date-of-birth-as-a-timestamp
You’ve never A/B tested unless you know for sure customers don’t prefer timestamps.

But joviality aside (wait, that was humour?), I did hit a problem along the way:

react-widgets-calendar-size-issue
That’s not so good, Al.

There is a quick fix to this.

Add in a local (S)CSS style:

.rw-popup-container.rw-calendar-popup {
  width: 24em !important;
}
redux-form-datetime-picker-react-widgets
Better

It’s good, but it’s not quite right. Good enough for me to continue, though has been firmly lodged into the ticket queue under ‘improvement’.

Here’s what it should look like:

react-widgets-datetime-picker-proper

So there you go. Hope it helps someone. It’s unofficial. It’s not the real fix. Any pointers appreciated.