“Using Functions as Children and Render Props in React Components” #reactjs #javascript

“Using Functions as Children and Render Props in React Components”  #reactjs #javascript

  • Here we are using the component, passing in a function, and then returning some content.
  • The component is able to manage all the state without leaking it’s logic into any other component.
  • This type of component is applicable for times when you need to reload the specific data each time.
  • Additionally if there is additional logic like sticky headers, the outer component doesn’t need to know anything about the logic required to do so.
  • With children as functions we are still able to compose our components like any other React component.

React allows for you to specify a function as a child, which children is just a normal prop so it is equivalent to a render callback.
Continue reading ““Using Functions as Children and Render Props in React Components” #reactjs #javascript”

Best practices for JavaScript function parameters

  • The problem with passing an object as a parameter to a function is that it’s not clear what values you should put into it.
  • One common thing in FP is to partially apply your functions, which is much harder to do if your function takes its parameters as an object.
  • While separate parameters are a good starting point, we run into trouble as soon as the function has optional parameters.
  • For functions with a single optional parameter, the solution is simple:

    Best practice: optionals come last

    However, if we have more than one optional parameter, the problem is… what if we only need to pass one optional parameter?

  • You can pass in parameters easily as an object, but the properties for the object can be easily seen from the function’s signature.

From time to time, people ask things like “should I use objects to pass function arguments”. I’m sure you recognize the pattern, as it’s common with many libraries:
Continue reading “Best practices for JavaScript function parameters”

Recreating the Chrome Console in React – LogRocket

  • Since a session could potentially have thousands of logs, we knew that we’d need to build a virtual list where DOM nodes are unmounted when they leave the viewport.User-interactive JSON treeExpanding objects in the Chrome ConsoleLike the Chrome javascript console, users should be able to expand objects that were logged.
  • Simply knowing the length of the list and having a rowRenderer function that can render a given row is all it needs!Our ImplementationI’m not going to describe every detail of our console implementation since much of it is a standard application of react-virtualized, but there are a few bits where we diverged that are interesting.Row HeightsAs I described earlier, react-virtualized takes a prop rowHeight which is a function that returns the height of a row at a given index.In this screenshot of the LogRocket log viewer, notice that there are 2 states for each row: default, and expanded.
  • However, when a row is expanded, its height varies as the user expands different subtrees of the object.We needed a way to write a rowHeight function that handles dynamic height rows- something like this:In order to implement getExpandedRowHeight in the above psuedo-code, there were two potential options.Guarantee deterministic height of an expanded objectTo achieve this, we would have needed to design the object tree view component from the ground up to make its height a pure function of the subtrees that are expanded.
  • Also, making this guarantee would make it difficult to iterate on the look and feel of the log viewer since changes to things like margins and padding would need to be adjusted for.Use react-measureInstead, we opted to use a library called react-measure which provides a helpful abstraction for writing components that are aware of their own height.react-measure wraps a given component and takes a prop, onResize which is a function that is called whenever the component’s size changes.In our case, whenever the size of a given row changes, we dispatch a Redux action which stores the height of that row in Redux.
  • Then in our rowHeight function, we simply get the height of the row from Redux, and react-virtualized can render it properly.There is a small performance penalty to this approach, since react-measure uses the DOM resize-observer API which isn’t implemented natively in all browsers, but in practice this is fairly minimal.Apollo ClientTo handle data fetching, we use apollo-client which is a GraphQL client that works nicely in React apps.

One of the core features of LogRocket is the replay of console and Redux logs in production web apps. To do this, you add the LogRocket SDK to your app which sends logs to LogRocket. Then, when…
Continue reading “Recreating the Chrome Console in React – LogRocket”

How to Animate the Items of a React Native FlatList

  • Be sure to subscribe!Animating EntryTo easily demo our animation we’ll animated to insertion of the list item.
  • When a new item is added to the people array we’ll change the opacity of the row and, via transform, the scale and rotation.It’s important to note that inside the TouchableOpacity we’re using an Animated.View which allows us to modify that component using animated values.First we’ll create a new animated value and, when the component mounts, we’ll change that value from 0 to 1 using Animated.timing.Then we need to drive our UI from these values.
  • We can’t do that in componentWillUnmout because the component will be gone before any animations can run!If you test this out though you’ll see that it doesn’t actually do anything — the row just disappears the same as before.If you comment out the onRemove function you can see that the animation is happening.What we can do is call the onRemove function when the animation completes.
  • We’re now left with some subtle, yet slick, animations for each row item for whenever they’re added or removed.
  • It covers component design, Redux, Redux Saga, and more animations!Want more React Native videos?

I was recently asked about animating items in a React Native list — specifically animating the item when added and removed. That’s what we’ll cover today! To accomplish this we’ll use the FlatList…
Continue reading “How to Animate the Items of a React Native FlatList”

Testing with Mocha – Kevin Wang – Medium

Testing with Mocha  #tdd #react #mocha #javascript #reactjs

  • js file and running “npm test” in the console.var assert = function() { describe(‘#indexOf()’, function() { it(‘should return -1 when the value is not present’, function() { assert.equal(-1, [1,2,3].
  • indexOf(4)); }); });});The test should pass and you should see the below.From the example above though, the function that the test is testing for is written in the same file.
  • toFixed(2) }, sleepApneaIncrease: function(amount){ return (amount * 1.06).
  • toFixed(2) }, heartDiseaseIncrease: function(amount){ return (amount * 1.17).
  • toFixed(2) }, checkCondition: function(amount, condition){ switch (condition) { case “Allergies”: return case “Sleep Apnea”: return case “Heart Disease”: return default: return 0; } }}I store them all in an object so thatI am able to export out and require them when I need to.

My first experience with Mocha is at Flatiron. When we were doing Javascript labs/work we used Mocha to test out the code that we wrote, it made sure that the results are as we expected. This was my…
Continue reading “Testing with Mocha – Kevin Wang – Medium”

Why Angular 2 Is So Awesome – Jacob Gardner – Medium

Why Angular 2 Is So Awesome  #react #angular2 #angular #javascript #reactjs

  • First you start with a simple route that looks something like this:{ component: SweetComponent, path: ‘fabulousness/:someId’}Pretty straightforward, yeah?
  • Okay, time to dig down into that SweetComponent from earlier and see how it accesses those fields.Your route is polite enough to provide Observables so that the component can make any necessary updates when the route changes, like this:route.params.subscribe(({ someId }) = otherStuff }) = …Convenient, huh?
  • Simply put, it’s a hash of the names for component properties that have changed to corresponding SimpleChange objects.
  • On that note, I’ll just defer to a passage from my entirely hypothetical and nonexistent previous article, Why TypeScript Is So Awesome:Unfortunately, TypeScript’s philosophy tends to encourage a developer to encapsulate values in ES6 classes, much as one would use structs in other languages.
  • When we obfuscate the true nature of JavaScript’s dynamic typing and prototypal inheritance behind a facade of static types and classes, we directly harm inexperienced developers by giving them a false impression of how JavaScript actually works.

Did you want to know what’s so great about Angular 2? Man, that sure was rhetorical. I’m definitely going to tell you regardless. Let’s talk routing; every app worth its salt needs routing. First you…
Continue reading “Why Angular 2 Is So Awesome – Jacob Gardner – Medium”

Optimizing React Performance with Stateless Components — SitePoint

Optimizing React Performance with Stateless Components  #reactjs #javascript

  • First, the Super Basics
    import React, { Component } from ‘react’

    class User extends Component {
    render() {
    const { name, highlighted, userSelected } = this.props
    console.log(‘Hey User is being rendered for’, [name, highlighted])
    return div
    h3
    style={{fontStyle: highlighted ?

  • For example, something like this:
    import React, { Component } from ‘react’

    class Users extends Component {
    constructor(props) {
    super(props)
    this.state = {
    otherData: null,
    users: [{name: ‘John Doe’, highlighted: false}]
    }
    }

    async componentDidMount() {
    try {
    let response = await let data = await response.json()
    this.setState({otherData: data})
    } catch(err) {
    throw err
    }
    }

    toggleUserHighlight(user) {
    this.setState(prevState = {
    users: prevState.users.map(u = {
    if (u.name === user.name) {
    u.highlighted = !

  • import React, { PureComponent } from ‘react’

    class User extends PureComponent {

    render() {
    const { name, highlighted, userSelected } = this.props
    console.log(‘Hey User is being rendered for’, [name, highlighted])
    return div
    h3
    style={{fontStyle: highlighted ?

  • Our first attempt at re-writing it back to a functional component but with recompose.pure looks like this:
    import React from ‘react’
    import { pure } from ‘recompose’

    const User = pure(({ name, highlighted, userSelected }) = {
    console.log(‘Hey User is being rendered for’, [name, highlighted])
    return div
    h3
    style={{fontStyle: highlighted ?

  • ‘italic’ : ‘normal’}}
    onClick={event = {
    userSelected()
    }}{name}/h3
    /div
    })

    export default User

    As you might notice, if you run this, the User component still re-renders even though the props (the name and highlighted keys) don’t change.

Writing inefficient React components can cause them to rerender too often. Peter Bengtsson looks at ways of creating and optimizing stateless components.
Continue reading “Optimizing React Performance with Stateless Components — SitePoint”