Skip to content

Instantly share code, notes, and snippets.

@mattpocock
Last active June 9, 2019 09:35
Show Gist options
  • Save mattpocock/fc9ce87197117ad05381fa4a959e2ea9 to your computer and use it in GitHub Desktop.
Save mattpocock/fc9ce87197117ad05381fa4a959e2ea9 to your computer and use it in GitHub Desktop.

Switching Props based on clients

Getting rid of region tags is a tough problem. It's not tough technically - it can be done in lots of different ways. But working out the best way is tough.

The options

clientSwitchValue

const someValue = clientSwitchValue({
  amc: true,
  itv: false,
  'drg,cineflix': false,
  default: true,
})

This simple API is probably the most effective for doing simple switches. It can handle lots of different cases, and forms the base API for other implementations.

The trouble is that only using it incentivises bad patterns. Let's say you need to change the className of a button in one use case (in an action menu, for instance) for drg only. Wherever you use the button, you'll want to add a clientSwitchValue.

withClientSwitchProps

const ActionMenuButton = () => {...}

export default compose(
  withClientSwitchProps({
    drg: {
      useLargeButton: true
    }
  })
)(ActionMenuButton)

This seems like a happier API to me for many use cases with React components. Instead of adding region tags for the drg case, you extend the component with props and add a withClientSwitchProps. You can then use the component without altering it as you use it, and it will pick up its extra props at runtime.

This gives two advantages. First, you can test components without changing over the __CLIENT__ global. This means it's possible to run unit tests that test all uses of the component across clients in a CI - crucial for test confidence.

Secondly, it helps with understanding the code. Currently, sometimes you have no idea why a region tag exists, only that it does. This new method helps to give intention to each client switch, which makes it easier to read.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment