FACEBOOK
TWITTER
LINKEDIN
SOCIALICON
SOCIALICON
Miloš Ristić – Web Development

How to handle ‘this’ in React

What’s real binding problem?

And answer is very simple: “With ES6 Classes, React doesn’t auto-bind the functions inside that component and you can’t use that function in render for example. However, there’re few methods how we can bind ‘this’ manually.

#1 Bind in render function

This method can cause some performance issues, as this function will be called every time component re-render and sometimes it can be so bad for our application.

 
#2 Use ES6 arrow function in render function

This method is pretty much the same as method #1 because it will call function every time component re-render, too.

 
#3 Arrow function in Class property

This method avoid perfomance issues from methods #1 and #2, but however it’s not strongly recommended to use, because it’s still experimental features which are not in offical ECMAScript specifications.

 

#4 Bind in constructor

This method also avoid performance issues from method #1 and #2, and because it’s not actually experimental, I will recommend to use this method as much as you can when you want to bind ‘this’.

 
Conclusion
There’re several methods how you can bind this, but as I already mentioned, I recommend to use “Bind in constructor” method before the others three. However, for some simpler components, you can use whatever method you like.

Fetch data in React

Web scraping using Fetch

Web scraping or web harvesting is method we’re using to get some data from other websites. I found out that Fetch method is much more easier to use than other methods to get data, like axios etc. However, Fetch has two main differences from jQuery.ajax() method:
 

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500.
  • By default, Fetch won’t send or receive any cookies from the server

 
Fetch in React (example)
 
Firstly, we need to have state where we can store data . We will create empty state called data. In function getDataFromApi we will fetch data from simple json provided by facebook – https://facebook.github.io/react-native/movies.json <- this one. Also, we should be sure that our response will be json and for that purpose we'll call response => response.json(). After that in response we have data from that JSON file and we will send that data to our previous defined state called with same name. At the end, we just need to map that data, to make list of items, and use their properties, like title.
 

 
Get HTML instead of JSON
 
As you can see, here, we’re using two npm packages – cheerio and react-render-html to display HTML we’ve got. Cheerio is package which allows us to use almost standard jQuery selectors to get right elements from HTML. After we do that, we pass those elements to new state and render it in render function by using renderHTML from the other package called react-render-html.
 

 
Conclusion
 
To Fetch data in React, we can simply use fetch to get all data we want. However, to do something more with that data, we can use ES6 map to show list from JSON, or cheerio to display HTML codes at our website.

JSX in depth: Fragments usage

What’s JSX?

JSX is a syntax extension to JavaScript. JSX produces React “elements”. If you’re not familiar with JSX, please consider to go through this React blog post before you continue to read this one. In this post, I will try to explain fragments in JSX as one advanced, but also easy-to-use concept in React.
 
 
Fragments

As React documentation says:

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

 
 
The simplest example

Fragments are used to replace “parent” JSX tag, when we don’t want it at all. Below, you can find the simplest example of using Fragments. In this example, we have three divs in component, but however, we want just these three divs to display, when user render that component.
 
class ThreeDivsFragments extends React.Component {
  render() {
    return (
      <React.Fragment>
        <div>First</div>
        <div>Second</div>
        <div>Third</div>
      </React.Fragment>
    );
  }
}

 
As you see, we’re using React.Fragment as holder for those three divs. If you know some basic stuffs regarding JSX, you know that JSX must contain one parent element to hold all children, and it’s usually looks like this:
 
class ThreeDivsOrdinary extends React.Component {
  render() {
    return (
      <div>
        <div>First</div>
        <div>Second</div>
        <div>Third</div>
      </div>
    );
  }
}

 
Now, let’s consider rendering of this component called ThreeDivs in both cases and see what’s output looks like in both cases.

<ThreeDivsFragments />

/* This returns ->
---------------------------------------
  <div>First</div>
  <div>Second</div>
  <div>Third</div>
---------------------------------------
*/

<ThreeDivsOrdinary />
/* This returns ->
--------------------------------------
<div>
  <div>First</div>
  <div>Second</div>
  <div>Third</div>
</div>
--------------------------------------
*/

 
And as you can see, ordinary usage of JSX require one more parent div. If we don’t want it, we should use React.Fragment. However, the biggest motivation for React develops to create Fragments was exactly to return a list of children – without any parent element. In React documentation, there’s one great example of using Fragments:

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }
}

 
And only with usage of Fragments, we can make 100% correct table HTML markup like:

<table>
  <tr>
    <td>Hello</td>
    <td>World</td>
  </tr>
</table>

 
Short syntax for Fragments is <>, so Columns component can also looks like:

class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }
}

 
Also, Fragments can have key attribute. A use case for this is mapping a collection to an array of fragments — for example, to create a description list. There’s an example in React documentation for this:

function Glossary(props) {
    return (
      <dl>
        {props.items.map(item => (
          // Without the `key`, React will fire a key warning
          <React.Fragment key={item.id}>
            <dt>{item.term}</dt>
            <dd>{item.description}</dd>
          </React.Fragment>
        ))}
      </dl>
    );
}

 
Conclusion
 
By using Fragments, you can avoid to create unnecessary parent elements to list of children. Also, it can help you to avoid many CSS problems regarding CSS selectors. It’s really simple to use, but you can save a lot of time using this concept, so I recommend to use it.

Simple To-Do App using React Context API

In this post, we learned a basics of React Context API. However, we need to learn how to put that Context API in practice.
 
What will we do?
 
We will create simple to-do application with one input field and button “Add item” for adding new item to our list. Also, we will have “Remove” button for every item, so we can remove them after job’s done.
 

 
Coding time!
 
Firstly, we will create new ToDoContext.

const ToDoContext = React.createContext();

After that, we will create new Provider, our to-do list, and there we will define all functions and states. As you can see, we have two states. First state contains values of default to-do items – list and also empty todo state. We have one function – createNewToDoItem for creating new item, and another one – deleteItem to remove item from list. Those functions are the same as functions without Context API, no changes at all. Also, we will have two functions to handle Enter for submit new item and to handle input changes. All those four functions should look like this:

constructor(props) {
  super(props);

  this.state = {
    list: [
      {
        todo: "clean the house"
      },
      {
        todo: "buy milk"
      }
    ],
    todo: ""
  };
}

createNewToDoItem = () => {
  this.setState(({ list, todo }) => ({
    list: [
      ...list,
      {
        todo: todo
      }
    ],
    todo: ""
  }));
};

deleteItem = indexToDelete => {
  this.setState(({ list }) => ({
    list: list.filter((ToDoList, index) => index !== indexToDelete)
  }));
};

handleKeyPress = e => {
  if (e.target.value !== "") {
    if (e.key === "Enter") {
      this.createNewToDoItem();
    }
  }
};

handleInput = e => {
  this.setState({
    todo: e.target.value
  });
};

Now, we should properly pass values from Provider to Consumer – we want to pass down list and also deleteItem function. We will not pass down createNewToDoItem, if you’re wondering why – that’s because it’s not function for single item. It’s globally for whole list and we don’t want to pass down it unnecessary. Our Provider should contains text input and “Add item” button and also should pass down props to children components.

<ToDoContext.Provider
  value={{ list: this.state.list, deleteItem: this.deleteItem }}
>
  <div className="ToDo">
    <h1 className="ToDo-Header">
      Simple To-Do App using React Context API
    </h1>
    <div className="ToDo-Container">
      <input
        type="text"
        value={this.state.todo}
        onChange={this.handleInput}
        onKeyPress={this.handleKeyPress}
      />

      <button className="ToDo-Add" onClick={this.createNewToDoItem}>
        ADD ITEM
      </button>

    </div>
  </div>

  {this.props.children}
</ToDoContext.Provider>

Consumer will use list and deleteItem function passed from Provider. With list, we will render items in to-do list, while deleteItem will be used to remove item with same index.

<ToDoContext.Consumer>
  {({ list, deleteItem }) =>
    list.map((item, key) => {
      return (
        <div key={key}>
          {item.todo}
          <button
            className="ToDoItem-Delete"
            onClick={deleteItem.bind(this, key)}
          >
            REMOVE
          </button>
        </div>
      );
    })
  }
</ToDoContext.Consumer>

Finally, in our App, we should make Consumer nested inside Provider like:

<div className="App">
  <ToDoList>
    <ToDoItems />
  </ToDoList>

</div>

 
Conclusion
 
By using prop drilling we pass list of items and deleteItem to our to-do items. If this was too hrad for you to follow, I provided example here in codesandbox, so you can play with those states, etc – https://codesandbox.io/s/zzqml2m2y4

React Context API – The simplest way

React documentation says:

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

I will try to explain this API in simple words.
 
 
When to use context?
 
If you need to pass one shared prop to many components. This prop is “global” for a tree of React components. The right term for this is – prop drilling.
 
 
Context API & Redux
 
Actually, React context API’s purpose is more or less same as Redux’s purpose. What’s the most important is simplicity. Context API is much simpler than Redux.
 
 
React.createContext
 
const {Provider, Consumer} = React.createContext(defaultValue);
//or
const ContextName = React.createContext();

 
With this we will have {Provider, Consumer} pair. When React renders a context Consumer, it will read the current context value from the closest matching Provider above it in the tree. The defaultValue argument is only used by a Consumer when it does not have a matching Provider above it in the tree.
 
 
Provider & Consumer – Roles
 
Provider is React component that allows Consumers to subscribe to context changes. Consumer is React component that subscribes to context changes and use that.
 
 
Example
 
Note: You can find full code of this example here.
 
In this example, we will create context and use it with two consumers. Those consumers will change background and font color in div dynamically according to value user pass through input field in provider.
Firstly, we need to create context with default value.
 
const ColorContext = React.createContext("#FFFF66");
 
After that we will create Provider:
class ColorProvider extends React.Component {
  state = { color: "#FFFF66" };

  getColor = event => {
    var targetValue = event.target.value;
      this.setState(({ color }) => ({
      color: targetValue
    }));
  };

  render() {
    return (
      <ColorContext.Provider value={this.state.color}>
        <input type="text" value={this.state.color} onChange={this.getColor} />
        {this.props.children}
      </ColorContext.Provider>
    );
  }
}

 
As you can see, we define Provider as ContextName.Provider, in this case ColorContext.Provider. But we must also pass props to children components by using {this.props.children} – this is important. From this point, our consumers can use value Provider pass.
 
class ColorConsumer extends React.Component {
  render() {
    return (
      <ColorContext.Consumer>
        {color => <div style={{ backgroundColor: color }}>{color}</div>}
      </ColorContext.Consumer>
    );
  }
}

 
As you can see, we define Consumer as ContextName.Consumer, in this case ColorContext.Consumer. After that, he can use value Provider passed to this component – in this case – it’s color. However, Consumer will use that value (prop) only if it’s child of Provider, so we must create proper tree in our rendering component, like:

<ColorProvider>
  <ColorConsumer />
</ColorProvider>

 
 
Conclusion
 
The newest React Context API is perfect solution for passing down props to children components, without explicitly passing it from parent component. Also, it’s great for props drilling when you don’t want to play around with much more complex and exhausting Redux or MobX.