Handling events and callbacks in ReactJS

Leave a comment

https://facebook.github.io/react/docs/thinking-in-react.html

So I have been studying ReactJS that last couple weeks. Mostly banging my head trying to come up with simple examples. Here is one based on Thinking in React that demos how to do callbacks.

Starting simple

Here is a simple bit of code that counts words.

Screen Shot 2017-09-01 at 8.44.25 AM.png

Note the main component is called ‘WordCount’, and it does a fine job of counting words.

Adding composition and parent callbacks

But what I want to do is create a sub-component, maintain the state in the parent component, and have the parent component pass it’s callback down to the subcomponent so it can be called back.

Here is what I got working.

Screen Shot 2017-09-01 at 8.47.15 AM.png

Note the following.

  1. Child calls parent callback

I don’t know if this is common, or even necessary, but based on the Thinking in React example this is what they do.

You define your parent callback like so

Screen Shot 2017-09-01 at 8.49.31 AM.png

And then you pass it to your child like so:

Screen Shot 2017-09-01 at 8.50.04 AM.png

Note the name pattern. ‘onSomething’ ‘handleSomething’. This I have seen in many examples and this seems common.

But then in the child you define another similar callback, and have it do nothing more than prep the data and call the parent.

Screen Shot 2017-09-01 at 8.51.20 AM.png

I don’t know what you would do this. I guess if you wanted to do some more processing (you know the saying about always adding another layer of indirection).

And then you use this child callback locally which in turn calls the parent callback we just defined.

Screen Shot 2017-09-01 at 8.53.06 AM.png

This works. I am just not sure if it’s right or needed.

What I would have expected to be able to do, is just pass the parent callback directly to the child component itself.

But I haven’t been able to figure out how to do that yet. Stay tuned…

Advertisements

How to pass anonymous arrow functions ReactJS

Leave a comment

You define the callback like this

Screen Shot 2017-08-31 at 8.31.52 AM.png

You pass it using the arrow functions like this

Screen Shot 2017-08-31 at 8.32.28 AM.png

You set it’s parameter values like this:

Screen Shot 2017-08-31 at 8.35.38 AM.png

You pass it to other components and functions like this

Screen Shot 2017-08-31 at 8.33.10 AM.png

And you add it to your controls like this

Screen Shot 2017-08-31 at 8.33.43 AM.png

ReactJS example using callback with User

Leave a comment

https://medium.freecodecamp.org/why-arrow-functions-and-bind-in-reacts-render-are-problematic-f1c08b060e36

Here is a simple example that showing the plumbing for a ReactJS app using a callback.

Screen Shot 2017-08-30 at 10.10.22 AM.png

import React from 'react';
import { render } from 'react-dom';

class User extends React.PureComponent {
  render() {
    const {name, onDeleteClick } = this.props
    console.log(`${name} just rendered`);
    return (
      <li>             
        <input 
          type="button" 
          value="Delete" 
          onClick={onDeleteClick} 
        /> 
        {name}
      </li>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        { id: 1, name: 'Cory' }, 
        { id: 2, name: 'Meg' }, 
        { id: 3, name: 'Bob' }
      ]
    };
  }
  
  deleteUser = id => {
    this.setState(prevState => {
      return { 
        users: prevState.users.filter( user => user.id !== id)
      }
    })
  }

  render() {
    return (
      <div>
        <h1>Users</h1>
        <ul>
        { 
          this.state.users.map( user => {
            return <User 
              key={user.id} 
              name={user.name} 
              onDeleteClick={() => this.deleteUser(user.id)} />
          })
        }
        </ul>
      </div>
    );
  }
}

export default App;

render(<App />, document.getElementById('root'));

JavaScript Scope

Leave a comment

https://scotch.io/tutorials/understanding-scope-in-javascript#toc-scope-in-javascript

When you start typing in JS you are in global scope.

Screen Shot 2017-08-29 at 2.22.08 PM.png

Variables defined inside a function are in the local scope. Meaning they have a different scope for every call of that function.

Screen Shot 2017-08-29 at 2.24.02 PM.png

Block statements

Contrary to the ‘var’ keyword, ‘let’ and ‘const’ support the declaration of local scope inside block statements.

Screen Shot 2017-08-29 at 2.27.18 PM.png

Difference between let and const?

‘const’ is a signal that the identifier won’t be reassigned.
‘let’ is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm.

Both have block statement scope.

Context

Many developers think scope and context are the same thing. They are not. Scope is what we talked about previously. Context is ued to refer to the value of ‘this’ in some particular part of your code.

Scope refers to the visibility of variables and context refers to the value of ‘this’.

Lexical Scope

Means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as Static Scope.

Screen Shot 2017-08-29 at 2.38.44 PM.png

Closures

Closures are closely related to Lexical Scope. A closure is created when an inner function tries to access the scope chain of its outer function. Closures contain their own scope chain, their parents, and the global scope.

When you return an inner function from a function, that returned function will not be called when you try to call the outer function. You must first save the invocation of the outer function in a separate variables and then call the variable as a function.

Screen Shot 2017-08-29 at 2.43.03 PM.png

Key thing to note here is that ‘greetLetter’ can access the name variable in the greet function even after it has returned. One way to call the returned function without doing the variable assignment is to call it with () x2 like this.

Screen Shot 2017-08-29 at 2.45.43 PM.png

Note: This still works.

Screen Shot 2017-08-30 at 7.23.16 AM.png

The difference in the previous example is the return statement. It only gets invoked when you do the ()().

Public and Private Scope

JS doesn’t have concepts found public, protected, private. Instead it emulates these features using closures. Which is basically nothing more than locally scope variables and functions.

Screen Shot 2017-08-30 at 7.15.03 AM.png

The Module Pattern

Screen Shot 2017-08-30 at 7.15.57 AM.png

This module pattern is a way to define Objects (functions) in JS that exposes public methods via a return statement while keeping private methods inside.

Screen Shot 2017-08-30 at 7.18.07 AM.png

Immediately-Invoked Function Expression (IIFE)

Screen Shot 2017-08-30 at 7.19.40 AM.png

Changing Context with .call(), .apply(), and .bind()

Call and Apply functions change the context of the function you are calling.

Screen Shot 2017-08-30 at 7.24.52 AM.png

The difference between .call() and .apply() is that in call you pass the arguments as a comma separated list, while in apply you pass them as an array.

Screen Shot 2017-08-30 at 7.28.19 AM.png

JavaScript Value vs Reference

Leave a comment

JavaScript has 5 data types that are copied by value. We call these primitives:
– Boolean
– null
– undefined
– String
– Number

And 3 data types that are copied by reference. We call these Objects:
– Array
– Function
– Object

Pure functions

Any function that doesn’t affect anything outside it’s outside scope is called a pure function. A function made up of primitives is a pure function. An Array passed in as an argument, that gets something pushed onto it, would affect the outside scope array. It’s change would persist to the outer scope and can lead to bugs that are hard to track down.

That’s why Array.map and Array.filter return copies of the Array they operate on and were written as pure functions.

Test

See if you can decode what’s going on here.

Screen Shot 2017-08-29 at 1.45.07 PM.png

We start off with personObj1, pass it into the function, assign it an age of 30, and then point it to a new object instance before returning and assigning it to a new variable.

Here is the actual output

Screen Shot 2017-08-29 at 1.46.42 PM.png

Get it? personObj1 is passed by reference to the method. So method has a pointer to personObj1 and assigns it a new age of 25. It’s done.

Screen Shot 2017-08-29 at 1.47.56 PM.png

This next line of code is the tricky one.

Screen Shot 2017-08-29 at 1.48.30 PM.png

This chunk of code reassigns the pointer that was pointing to personObj1 to a new object – John 50 and returns it.

Screen Shot 2017-08-29 at 1.49.25 PM.png

The reassignment does not change personObj1. It remains intact. person has a new reference because it was reassigned. But reassign doesn’t change original. The equivalent above would be the following.

Screen Shot 2017-08-29 at 1.51.17 PM.png

Links that help

These notes were based on the excellent links found here:
https://www.educative.io/collection/page/5679346740101120/5707702298738688/5685265389584384

Template literals

Leave a comment

I was doing some reactjs examples and I came across this strange syntax for invoking JS. Something called a template literal.

Screen Shot 2017-08-29 at 8.03.23 AM.png

Screen Shot 2017-08-29 at 8.04.30 AM.png

JavaScript arguments and Rest parameter syntax

Leave a comment

https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

Functions

Here is a basic JS function

Screen Shot 2017-08-29 at 7.40.12 AM.png

Functions have parameters, but they also have access to additional variable called arguments, which is an array-like object holding all of the values passed to the function.

Here is how we could re-write the function to take as many arguments as we want

Screen Shot 2017-08-29 at 7.45.10 AM.png

This is useful, but a little verbose. To diminish the code a bit more we can substitute the arguments array with Rest parameter syntax.

In this way we can pass in any number of arguments while keeping our code minimal.

Screen Shot 2017-08-29 at 7.52.47 AM.png

Rest in this context means ‘rest of the arguments’.

More

JS let’s you create anonymous functions

Screen Shot 2017-08-29 at 7.55.34 AM.png

But what if you want to call a function recursively? JS lets you create named function expressions (IIFEs or Immediately Invoked Function Expressions) like so.

Screen Shot 2017-08-29 at 7.57.35 AM.png

Links that help
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript

Older Entries Newer Entries

%d bloggers like this: