Don’t let JS turmoil stop you from learning

Alex Standiford:

I have been reluctant to learn a modern JS framework because the network has felt too volatile for me to make a jump, and I really don’t see a point in learning something until I decide to use it in my daily workflow. I invest my time in getting really good at the tools I use instead of pretty good at a bunch of different tools.

Once the community makes this decision, I have a solid reason to learn one of these frameworks. Until then, I’ll just stick with jQuery, even though I dislike it.

This is not an uncommon sentiment, so I thought it would be useful to share my response:

The counter to this is that a number of the frameworks share concepts that are broadly applicable. Understanding what a component is applies to React, Vue, Angular and others. The knowledge transfers, even if the specific implementations are different between them, so there isn’t a reason to avoid learning one. Understanding React makes learning Vue easier, and gives you a better sense of what trade-offs are made when choosing one over the other.

Also, many of these frameworks follow a similar Flux-y pattern (actions up, data down), which is additional knowledge that again transfers regardless of framework. The volatility in the JS community has settled down since a few years ago, and these concepts are broadly applicable, so I’d highly recommend picking one (usually React) and learning it as much for its concepts/approaches as its specific implementation.

Using Observables to Control Render Scheduling

When I talk to other developers about Observables, it’s often hard to explain their benefits because on the surface, they just look like glorified event emitters, but it’s how they compose that make handling dependencies between async events such a breeze. While working on the code snippet editor in WP-Gistpen, I came across an example that shows how easily Observables handle async behavior.

So here’s the setup: building a snippet editor on top of PrismJS and borrowing some code from Dabblet, both from Lea Verou, and using Redux as an Observable of states, we need to rerender the editor as the text changes, keeping the syntax highlighting up to date. We keep the position of the cursor and the value of the editor in the Store, allowing the reducer to be responsible for the complex logic that handling special text editor keystrokes, like enter, tab, etc.

The issue is rendering the editor requires us to track & reset the cursor, as we have to reset the text with the latest from the store and rehighlight it. If we do that while the user is typing, we have the potential to interrupt her, so we need to delay the render until the user is no longer typing. The render itself is scheduled in a requestAnimationFrame, so if the user types before the next frame, we need to cancel the render request and wait until the user stops typing again. Otherwise, when the frame renders, the cursor will jump back to the position it was at when the render was scheduled.

So this is the problem we’re trying to solve.

In brookjs, a component is just a function that takes a DOM element & a stream of props$ and returns a stream of (usually Flux Standard) Actions from the element. Since we’re given an Observable of state, we’re able to get pretty fine control over exactly when the editor renders.

I’m using Kefir, but the same concepts apply any other Observable implementation. Here’s how I solved this:

component.js

This problem is obviously solvable in a stateful way, with the view being responsible for holding onto a reference to the render loop, scheduling it in one event callback if a render isn’t scheduled and cancelling the render on the other if it is. We’re not talking about a huge component here, so there’s no reason to think managing this state would be difficult.

But as this component grows in complexity (and it will), colocating the temporal dependencies makes it very easy to reason about how the component changes over time. In the above example, how keyup and keydown events interact with the render cycle is explicit, rather than bouncing between callbacks or methods to see how animations are scheduled and cancelled. There’s zero chance of accidental cancellations or double renders.

Side effects, like updating the DOM, are wrapped in a stream, so they can be handled asynchonrously and cancelled, if needed. Because an Observable comes with its own cleanup code (the function returned at the end of stream‘s callback), when the active Observable is switched, the animation frame request for the previous Observable is cancelled, ensuring the user isn’t interrupted as she types. The props$ stream has control over when the render happens, and flatMapLatest ensures only the newest Observable is being observed at a time, so as the props$ emits new state, previous renders are also cancelled.

brookjs provides some structure around this paradigm, but underneath, this is all that’s happening, and it provides some elegant solutions to thorny async problems. The canonical example is the autocomplete box, sending an AJAX request as a user types and cancelling the previous request. This is explained by Jafar Husain in this great talk.

Even after writing this article, the editor rendering continued to get more complicated, and handling it with Observables allowed me to focus on how particular events interacted with the render cycle, without worrying about how to manage what was actually happening at a given time. Let me know if you think the current implementation is easy to understand.

This post is part of the thread: Project: WP-Gistpen - an ongoing story on this site. View the thread timeline for more context on this post.

I had been working on oEmbed into WP-Gistpen, so I wrote this tutorial on customizing oEmbed content from WordPress yourself. How have you been using the new oEmbed feature in WordPress?

This post is part of the thread: Personal Milestone - an ongoing story on this site. View the thread timeline for more context on this post.

Chatr: Implementing Server Side Rendering with React

In our introduction to the series, we got a simple static page rendered with express.js and handlebars. Now that we’ve got everything going, we’re going to leverage React’s server-side rendering to move from just sending some static HTML to sending a rendered component’s HTML. On the client side, we’ll bootstrap React into the rendered HTML using the same state that produced the HTML on the server, and the application can just pick up where it left off.

I was actually pretty impressed with how easy it was to get the actual server-side rendering working. However, the issue I had when I started was that I didn’t actually start with ES6 and JSX transpiling on the server to start, but it makes a lot of sense that, if your goal is to build an isomorphic JavaScript application, you should use the same syntax on both sides of the wire. Since you’re definitely going to need JSX transpiling on the server anyway, it’s easier to go all-out with the es2015 preset as well.

I got that working in the introduction to the series, even though it didn’t happen in that order in real life, so if you need a refresher, check that out. Now before we build our first React component, make sure you install react and react-dom via npm; these are the two main React tools we’re going to use in this project.

Just to get started with React, we’ll replicate the current Hello World! setup with a simple App component that takes a required headline as its props.

app.js

If this is your first introduction to React, you’ll notice the XML-like JSX syntax in the render function. This is transpiled by babel‘s JSX plugin into React calls that create the modeled DOM structure. For the most part, JSX works a like HTML, with JavaScript weaved into it, giving you a really powerful way of describing your UI state. Because it’s still JavaScript and class is a reserved word, you see above one of the many differences with plain HTML; we have to use className to give the DOM node a class. If we were to render it with headline as "Hello World!", the resulting HTML would look like this:

rendered.html

As for the other two props on the object: both them (displayName and propTypes) are primarily useful for development. One of React’s greatest strengths is the ecosystem of development tools that have cropped up around it; this feature comes built-in! You get console messages when the component receives props of the wrong type.

Ensuring that you’re validating your props’ values and types during development helps ensure nothing unexpected happens during production, so definitely get in the habit of defining your components’ propTypes along with its render method as part of a standard component. The React docs on "reusable components" has the full list of types and constraints you can put in your propTypes. The displayName is used in these log methods to indicate which component has the error, making it easier to debug where the problem is coming from.

This is a really simple component, but now we need to pass it props and render it. The process for doing that on the server side mirrors the client side, so let’s get it running on the server first.

In our main server.js file, we have to change the root (/) route to render this component instead of the static string we provided earlier. Here’s the new server.js code:

server.js

react-dom is React’s DOM rendering tools. These used to be bundled with React but they were split off in v0.14. They were split off from the main React package because React has ambitions beyond just the DOM, like react-native and others, so separating the packages makes sense for the project. These tools allow us to render the React components on the server as well as to the DOM; in this case, we’re using it to render the React component to a string, so the express server can send it to the client.

The first thing we do is set up the initial page state variable. As we build out the full application, this would be the point where we fetch the information from the database that’s required to render the page state. In our case, we’re just going to set our headline string.

From there, we just call ReactDOMServer.renderToString on the App component, passing in the state variable using JSX’s spread attributes to pass the object’s properties as the component’s props. This JSX syntax is modeled after ES6’s spread operator, allowing you to pass in the entire state object rather than just the props the component needs, which can be a bit more cumbersome for larger components.

Lastly, we stringify the state object so we can pass it into the view, where it’ll get received by the client code to boostrap the same React component.

On the client-side, we just need to bootstrap off the DOM node and state object we originally rendered with:

client.js

On the client side, we call the render method with the component as well as the DOM element to render onto. React will automatically pick up the fact that this is React-sourced HTML and instead of rerendering the whole page, will just attach the event listeners to the DOM, using the rendered data-reactid attributes.

From there, you can bootstrap your application however you’d like, depending upon how you choose to structure your application. In the next article, we’re going to start wiring up the RxJS streams, building a stream that will model our state as a series of messages as well functioning as a clearinghouse for all of the messages running through the client application. In this way, we’ll be able to direct those messages to and from the server and throughout the server application, with the UI just responding to state refreshes from this main stream.

This post is part of the thread: RxJS & React w/ Chatr - an ongoing story on this site. View the thread timeline for more context on this post.

CSS: Expanding a div to take up the remaining space in a row

I ran into a problem today. I had two elements next to each other on a row. I needed the first element to just be contained to the width of its child elements, while the second element needed to take up the rest of the space.

Here’s some dummy markup to get the idea:

original.html

The problem is, when I was using float left and right, I was setting the width of the second element manually using media queries, which worked at first but turned into a real bit of trouble when I attempted to make the containing element (a column wrapping the row) more responsive.

I couldn’t keep adding breakpoints and reset the size. Or I could, but it would be really brittle and would need to be updated every time the breakpoints of the containing element changed. I floundered around a bit, trying to find a solution, until I settled on this one, which relies on the oft-maligned table.

Not a <table> per se, but display: table. I have not used this feature much, since my CSS knowledge is generally pretty minimal, but there are a lot of places, like this one, where it’s going to be a lot more functional than the standard "float the div" method we’re all used to for building responsive layouts. Here’s how it works:

First, I needed to add an extra wrapper, so our HTML now looks like this:

updated.html

And our CSS looks like this:

styles.css

The nifty thing to notice is the .contained CSS. We set the width to be impossibly small, but tell the cell not wrap its contents. This has the effect of forcing the cell to expand to be the width of its contents, while allowing the .expanded div to take over the remaining space, achieving the effect I was looking for.

Do you know of any other uses for display: table that can’t be solved with the standard "float the div" method? Let me know in the comments.