React


Back to Tags

React event.code

🗓️ December 29, 2021

Turns out (at least at the time of writing this TIL), that react doesn’t include the code property on their Synthetic Events.

Namespace pattern in React

🗓️ March 04, 2021

So I’ve seen this pattern around but didn’t know it had a name! If you’ve ever used Context in React, you’re aware of there being a Provider and a Consumer and those two are namespaced to a specific Context. Keep in mind, this is assuming you’re using React < 16.8.0.

For example:

const SomeContext = React.createContext()

const SomeContextProvider = ({ children }) => {
  const [yolo, setYolo] = React.useState(false)

  return <SomeContext.Provider>{children}</SomeContext.Provider>}

const SomeContextConsumer = ({ children }) => {
  return (
    <SomeContext.Consumer>      {(context) => {
        if (context === undefined)
          throw new Error("Must be used within a SomeContextProvider")

        return children(context)
      }}
    </SomeContext.Consumer>
  )
}

I’m still trying to figure out when this should be used.

useLayoutEffect vs useEffect

🗓️ October 20, 2020

99% of the time you want to be using useEffect but there are some rare use cases for useLayoutEffect and I incidentally ran into one today at work 😂.

  • useLayoutEffect if you need to mutate the DOM and/or perform some measurements
  • useEffect if you don’t interact with the DOM at all.

Why React Elements have a "$$typeof" Property

🗓️ October 10, 2020

While making my way through a new React course, I learned that React elements have a $$typeof property to help mitigate issues with XSS attacks.

In essence, the $$typeof prevents anyone from trying to get React to create invalid elements via JSON. Even if a user passed in some JSON that mimicked what a React Node looks like, the value of $$typeof is a Symbol and this cannot be mocked by JSON!

Read More

Internationalization in React

🗓️ April 16, 2020

This technically isn’t something that I learned “today” but it is something that I wanted to make note of! If you’re ever working on a project and need to support internationalization, your library of choice— assuming you’re writing in React— should be react-i18next!

Why? My coworker Vincent wrote up a great ADR (Architectural Decision Record) and evaluated the library and some of the benefits it totes is…

  1. It has a hooks implementation so there’s no change needed to be made to the render portion (the view) of your React components.
  2. It generates translation files in a directory that can be easily handed off to a translator to populate
  3. There’s enterprise options available if ye need em!

Components and Inversion of Control

🗓️ November 21, 2019

A neat little concept that I learned about (just briefly) today is this idea of inversion of control. Essentially, assuming that we’re talking about React/Vue components, instead of having a mega component that accepts several different props to handle various things like position, aligment, etc, it sometimes make more sense to have a component that inverts control to the caller.

This means that we can extract out our business logic to a base component and then have specialized components that utilize the inversion of control to create a huge combination of different specializations/configurations. For exampe, we could have a Base Accordion that implements some core business logic and the rendering/extending can be left to a specialized implementation like Left aligned accordion or All can open acccordion.

The benefits of this pattern are the following:

  1. We no longer have to ship unncessary code to users — people only get the code that’s relevant to their use case
  2. Our bundle sizes will drop considerabley because of number 1
  3. We don’t fall victim to the “it’s only one more if statement” trap… if someone wants to extend our base component we expose the API’S they need to easily do this.
Thanks to Kent for the blog post!

Headless UI Components!😎

🗓️ October 25, 2019

A headless UI component is a component that offers up maximum flexibility by providing no interface itself! This sounds like a radical idea but for library authors, it’s a great pattern to provide their users with all that sweet sweet functionality that they’re craving without any of the bloat/stylystic decisions that come with interface decisions.

This pattern works great when the logic of a component is complex and can be decoupled from its visual representation.

From a React perspective, this can be acheived via an HOC, render props, or if you’re using React > 16.8, hooks. Below is an example of two different interface implementation of a very simple toggle — the state isn’t complicated but since we created this headless interface, the UI can easily be changed/edited and does not suffer from the opinions of the library author

The Example

renderProps
class Toggle extends React.Component {
  state = {
    on: false,
  }

  handleClick = (cb = () => {}) => evt => {
    this.setState({ on: !this.state.on }, () => cb(evt))
  }

  render() {
    const { state, handleClick } = this
    return this.props.children({ state, handleClick })
  }
}

function CheckBox() {
  return (
    <Toggle>
      {({ state, handleClick }) => {
        return (
          <input
            type="checkbox"
            id="scales"
            name="scales"
            checked={state.on}
            onChange={handleClick()}
          />
        )
      }}
    </Toggle>
  )
}

// Just some simple styled components
// to illustrate how we can decouple the styling from the logic
const Label = styled.label``
const Input = styled.input``
const Slider = styled.span``

function PrettyToggle() {
  return (
    <Toggle>
      {({ state, handleClick }) => {
        const appliedHandleClick = handleClick(console.log)
        return (
          <Label>
            <Input
              type="checkbox"
              checked={state.on}
              onChange={appliedHandleClick}
            />
            <Slider />
          </Label>
        )
      }}
    </Toggle>
  )
}
hooks
function useToggle(cb = () => {}) {
  const [on, updateClick] = React.useState(false)
  const event = React.useRef()

  React.useEffect(() => {
    cb(event)
  }, [on])

  return {
    on,
    handleClick(evt) {
      event.current = evt
      updateClick(!on)
    },
  }
}

function HookPrettyToggle() {
  const { on, handleClick } = useToggle(console.log)

  return (
    <label class="switch">
      <input type="checkbox" checked={on} onChange={handleClick} />
      <span class="slider round"></span>
    </label>
  )
}

function HookCheckBox() {
  const { on, handleClick } = useToggle()

  return (
    <input
      type="checkbox"
      id="scales"
      name="scales"
      checked={on}
      onChange={handleClick}
    />
  )
}