Will's avatar

Posts and notes React

(4 items)

Adding 'dark mode' and dynamic theming to your React websites 21 August 2021

Adding theming and the choice between “light” and “dark” modes to your website can enhance your site’s accessibility and make it feel more consistent with the host operating system’s own theme.

With JavaScript (and React in particular) this is easy to do, as I’ll explain in this post. We’ll use a combination of our own JavaScript code, the Zustand state management library, and the styled components package to achieve the following:

Read more...(8 minute read)

Code syntax highlighting in Gatsby 28 July 2021

Providing code snippets on your website or blog can be a great way to convey meaning for technical concepts.

Using the HTML pre tag can help provide structure to your listings, in terms of spacing and indentation, but highlighting keywords - as most people do in their code text editors - also vastly helps improve readability.

For example, consider the below JavaScript snippet.

class Greeter {
  greet(name) {
    console.log(`Hello, ${name}!`);
  }
}

const greeter = new Greeter();
greeter.greet('Will');

The exact same listing is displayed below with some simple syntax highlighting. The structure and meaning of the code becomes much easier to understand.

Read more...(2 minute read)

React State Management with Zustand 5 February 2021

React state

React state management is what gives the library its reactiveness. It’s what makes it so easy to build performant data-driven applications that dynamically update based on the underlying data. In this example the app would automatically update the calculation result as the user types in the input boxes:

import React, { useState } from 'react';

function MultiplicationCalculator() {
  const [number1, setNumber1] = useState(0);
  const [number2, setNumber2] = useState(0);
  return ( <>
    <input value={number1} onChange={e => setNumber1(parseInt(e.target.value))} />
    <input value={number2} onChange={e => setNumber2(parseInt(e.target.value))} />
    <p>The result is {number1 * number2}.</p>
  </> );
}

The resultant React app, showing two text inputs and a result line

Read more...(5 minute read)

React Query 15 December 2020

If you write React web apps that interface with a backend web API then definitely consider trying React Query.

The library makes use of modern React patterns, such as hooks, to keep code concise and readable. It probably means you can keep API calls directly inside your normal component code rather than setting-up your own client-side API interface modules.

React Query will also cache resolved data through unique “query keys”, so you can keep transitions in UIs fast with cached data without needing to rely on redux.

Read more...(1 minute read)