Tag Archives: React

Highlighting Bitmasks with React

The trend of resources (such as memory and disk space) becoming more abundant is still ongoing, and as a result, software development has become quite wasteful. While it’s quite common for an average application to guzzle several gigabytes of RAM nowadays, many people are not even aware that it’s possible to pack several pieces of information into the same byte. In fact, old games have been able to pack several pixels worth of data in a single byte, and this technique is still quite common for bit flags.

Bitmasks in Practice

Let’s consider a simple example: I have an RPG, where a character’s status can be one of the following values:

  • 1 = Paralysed
  • 2 = Poisoned
  • 4 = Diseased
  • 8 = Blind
  • 16 = Hungry
  • 32 = Fatigued

Using a power of two for each value means that I can use a single number to represent a combination of these values. For example:

  • 12 (decimal) = 001100 (binary) = Diseased and Blind
  • 2 (decimal) = 000010 (binary) = Poisoned
  • 63 (decimal) = 111111 (binary) = all six statuses apply

Each of these individual statuses is a flag with a boolean value. They are independent of each other and can be set simultaneously. By combining them into a single variable (called a bitmask) as shown above, we can store them more efficiently, both in memory and on disk.

The downside is that it becomes less readable. In order to know that a value of 21 means Hungry, Diseased and Paralysed, you need to break it down into individual bits and look up what each one means. That’s not a problem; in fact, we’ll build a little utility with React to help with this.

Listing the Bit Flags

We’re going to create a variation of the Filter List As You Type example that will list the individual flags and then highlight them based on user input. Start by creating a new React app. Once that’s done, open src/App.js and remove the logo import as well as everything inside the <header> tag so that you’re left with just this:

import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">

      </header>
    </div>
  );
}

export default App;

Next, create an object that maps the value of a flag to its description. This is just for display purposes. Inside the <header> element, use a simple map() function to display the flags (value and description) in a table:

import './App.css';

function App() {
  const flags = {
    1: 'Paralysed',
    2: 'Poisoned',
    4: 'Diseased',
    8: 'Blind',
    16: 'Hungry',
    32: 'Fatigued'
  };

  return (
    <div className="App">
      <header className="App-header">
        <table>
          <tbody>
          {
            Object.keys(flags).map(x => (
              <tr key={x}>
                <td>{x}</td>
                <td>{flags[x]}</td>
              </tr>))
          }
          </tbody>
        </table>
      </header>
    </div>
  );
}

export default App;

If you run npm start, you should be able to see the list of flags:

Listing the bit flags

Highlighting Bit Flags

Next, we’ll accept a bitmask (as a decimal number) as user input, and use it to highlight the relevant flags. This is very similar to what we did in Filter List As You Type with React, so start off by adding the relevant imports at the top of the file:

import React, { useState } from 'react';

Next, add the following to capture the state of the input field:

const [input, setInput] = useState('');

Add a text field right above the table:

        <input id="input"
          name="input"
          type="text"
          placeholder="Enter a bitmask in decimal"
          value={input}
          onChange={event => setInput(event.target.value)}
        />

Finally, we need to do the highlighting part. For this, we’ll add a getHighlightStyle() helper function, and use it on each row. The following is the full code for this article:

import React, { useState } from 'react';
import './App.css';

function App() {
  const flags = {
    1: 'Paralysed',
    2: 'Poisoned',
    4: 'Diseased',
    8: 'Blind',
    16: 'Hungry',
    32: 'Fatigued'
  };

  const [input, setInput] = useState('');

  const getHighlightStyle = flagValue =>
    (input & flagValue) > 0 ? { backgroundColor: 'red' } : null;

  return (
    <div className="App">
      <header className="App-header">
        <input id="input"
          name="input"
          type="text"
          placeholder="Enter a bitmask in decimal"
          value={input}
          onChange={event => setInput(event.target.value)}
        />
        <table>
          <tbody>
          {
            Object.keys(flags).map(value => (
              <tr key={value} style={getHighlightStyle(value)}>
                <td>{value}</td>
                <td>{flags[value]}</td>
              </tr>))
          }
          </tbody>
        </table>
      </header>
    </div>
  );
}

export default App;

We’re using the bitwise AND operator (&) to do a binary AND between the input and each flag. Let’s say the user enters 3 as the input. That’s 000011 in binary; so:

  • 000011 AND 000001 (Paralysed) results in 000001 (greater than zero);
  • similarly, 000011 AND 000010 (Poisoned) results in 000010 (also greater than zero);
  • however, 000011 AND 000100 (Diseased) results in 000000 (not greater than zero);
  • and so on.

This is a common way of determining whether individual bits are set, and it works quite nicely:

Flags are highlighted based on the bitmask in the text field

So that’s it: we’ve made a simple tool with React to help make sense of bitmasks, and hopefully learned a bit about bitmasks and bitwise operators along the way.

Filter List As You Type with React

A common piece of functionality in many user interfaces is to allow users to filter a list interactively by typing into a text field. In fact, I wrote an article showing how to do this in WPF almost seven years ago.

I’m currently learning React, and I feel this is a good exercise to get the hang of several basic concepts. I am sharing this in case it helps anyone, but my React knowledge is quite limited so I don’t expect anyone to take this as some kind of best practice. I welcome feedback on any possible improvements.

Although this article is quite basic, it covers several topics including controlled components, state manipulation, and keys. I’m not getting into the details of one-way binding and JSX, and just assuming you’re already familiar with them.

Preparing the React Application

The first thing to do is create a new React application. Simply follow the instructions in “Getting Started with React“.

Remove everything from src/App.css, and remove the <header> element from src/App.js as well as the logo import so that you are left with just this:

import React from 'react';
import './App.css';

function App() {
  return (
    <div className="App">

    </div>
  );
}

export default App;

If you’re using Visual Studio Code, you can use Ctrl+` (Control backtick) to bring up an integrated terminal. Either way, run npm start from a terminal. You should see an empty page because we just removed everything from it.

Showing a List of Fruit

If we’re going to filter a list, the first thing we need is to show a list. This is easy enough to achieve:

function App() {

  const fruit = ['apple', 'banana', 'orange', 'grapefruit',
    'mango', 'strawberry', 'peach', 'apricot'];

  return (
    <div className="App">
      <ul>
      {fruit.map(f => <li>{f}</li>)}
      </ul>
    </div>
  );
}

We’ve just got an array of strings representing different fruit, and we’re using the JavaScript map() function to render each item within a list.

The list is rendered, but we get a warning about a missing key.

If you save the file, the browser should automatically reload and display the list of fruit as shown above. However, if you open the browser’s developer tools, you’ll notice a warning about some missing key.

When rendering a list of items, React needs each item to be given a unique key to keep track of changes and know when it needs to re-render. This is done by adding a key attribute and binding it to something, as shown below.

      {fruit.map(f => <li key={f}>{f}</li>)}

In our case, we can simply use the name of the fruit itself, but typically you will want to use a unique ID rather than the display string.

State and Controlled Components

The next thing we need is to take input from a text field. We can show a text field by simply adding it to the JSX:

    <div className="App">
      <p>
        Type to filter the list:
        <input id="filter"
          name="filter"
          type="text"
        />
      </p>
      <ul>
      {fruit.map(f => <li key={f}>{f}</li>)}
      </ul>
    </div>

If we want to use the value of the text field (i.e. whatever the user is typing), then we need to link it to the component state. To get to this point, we’ll first introduce the useState() hook as follows:

import React, { useState } from 'react';
import './App.css';

function App() {

  const fruit = ['apple', 'banana', 'orange', 'grapefruit',
    'mango', 'strawberry', 'peach', 'apricot'];

  const [filter, setFilter] = useState('');

  // ...

useState() is simply a function that helps us work with component state, which is where we store any view-related data such as the filter text in our particular eample. Its purpose and functionality might be confusing at first glance, especially because the name is not particularly clear.

Basically, it takes an initial state as a parameter (an empty string in the case of the filter text), and returns an array of two items: the current state of a particular variable, and a function that can assign its value. These roughly correspond to a getter and a setter, except that the getter is the actual value rather than a function (whereas the setter is indeed a function).

We use destructuring to extract these two into separate variables. What’s interesting is that we don’t really need to implement anything more than what you see here: even the setFilter() function is given to us and we don’t need to define it.

Now that we have a way to get and set the filter text within the component’s state, we can update the input field to use this functionality:

        <input id="filter"
          name="filter"
          type="text"
          value={filter}
          onChange={event => setFilter(event.target.value)}
        />

Specifically, we use the current value of filter (from component state) to set the value attribute of the input field, and provide a React event (note the casing which distinguishes it from the onchange DOM event) that updates the component state whenever the value in the input field changes.

In this way, the filter text value in the DOM (input field) is always in sync with the component state, meaning that we can use the value in component state without ever having to touch the DOM directly. This is called a controlled component.

If you’re using the React Developer Tools extension for Chrome, you can see the state value being updated even though we haven’t implemented the list filtering functionality yet:

The component state reflects the value of the input field in the DOM.

Filtering the List

Since it is now easy to retrieve and manipulate the value of the filter text, filtering the list simply becomes a matter of using the JavaScript filter() function when rendering the list:

      <ul>
      {fruit.filter(f => f.includes(filter) || filter === '')
            .map(f => <li key={f}>{f}</li>)}
      </ul>

Each time a user types in the input field, this changes the state of the component, which causes React to re-render it. The list is updated accordingly in real-time:

Note that this filtering is case sensitive, so it won’t work as expected if you type uppercase characters. I didn’t include this level of detail to keep things as concise as possible, but it is easy to adapt this to handle case insensitive filtering.

Complete Code

If you followed the instructions so far, your src/App.js should look like this:

import React, { useState } from 'react';
import './App.css';

function App() {

  const fruit = ['apple', 'banana', 'orange', 'grapefruit',
    'mango', 'strawberry', 'peach', 'apricot'];

  const [filter, setFilter] = useState('');

  return (
    <div className="App">
      <p>
        Type to filter the list:
        <input id="filter"
          name="filter"
          type="text"
          value={filter}
          onChange={event => setFilter(event.target.value)}
        />
      </p>
      <ul>
      {fruit.filter(f => f.includes(filter) || filter === '')
            .map(f => <li key={f}>{f}</li>)}
      </ul>
    </div>
  );
}

export default App;

Summary

You should take away the following from this article:

  • When rendering lists of items, make sure to give each item a unique key.
  • The state of a component contains view-related data.
  • React hooks are simply functions providing ways to access state and life cycle.
  • useState() lets you get and set the value of a variable within state, and also provide an initial value.
  • A controlled component manages input fields (DOM elements) by linking their value to the React component state. This is done by binding an input field’s value to the component state, while at the same time using events to update the value in the component state when the value in the DOM changes.
  • State changes cause a React component to re-render.

Getting Started with React

React is a modern JavaScript library for building UI components. In this article, we will go through the steps needed to set up and run a React project. While there is much to be said about React, we will not really delve into theory here as the intention is to get up and running quickly.

Creating a Project

Like other web frontend libraries and frameworks, React requires npm. Therefore, the first thing to do is make sure you have Node.js installed, and if that is the case, then you should already have npm. You can use the following commands to check the version of each (making sure they are installed):

node -v
npm -v

We can then use Create React App to create our React project. Simply run the following command in your terminal:

npx create-react-app my-first-react-app

This will download the latest version of create-react-app automatically if it’s not already available. It takes a couple of minutes to run, and at the end, you will have a directory called my-first-react-app with a basic React project template inside it.

The output at the end (shown above) tells you about the directory that was created, and gives you a few basic commands to get started. In fact, we’ll use the last of those to fire up our web application:

cd my-first-react-app/
npm start

This will open a browser window or tab at the endpoint where the web application is running, which is localhost:3000 by default, and you should see the example page generated by Create React App, with a spinning React logo in it:

Open the project folder using your favourite text editor (e.g. Visual Studio Code), and you can see the project structure, as well as the App.js file which represents the current page:

With the web application still running, replace the highlighted line above (or any other you prefer) with “Hello world”. When you save, the running web application will automatically reload to reflect your changes:

And that’s all! As you can see, it’s quite easy (even if perhaps time-consuming) to create a React project. It’s also easy to run it, and since the project files are being watched, the running application is reloaded every time you save, making it very fast and efficient to make quick development iterations.

You are probably still wondering what React is, what you can do with it, and how/why there is markup within JavaScript! Those, my friend, are topics for another day. 🙂