[React Native] Using variable as JSON’s key instead of hardcoded string

tl;dr

A relatively short blogpost sharing why I use variable as JSON’s key in React Native.

Introduction

As we all know that, JSON is key-value paired. See below code.

// A JSON
const json = {
  name: "Yik Kok",
  website: "www.yikkok.com"
}

Well, inside the curly brace, left hand side is the key and right hand side is the value.

Is that possible to replace the key with variable ? Yes, it is possible.

** But why ? (Well, I found it’s quite useful, I will explain my thought later)

Let see the code below.

const NAME = "name";
const WEBSITE = "website";

const json = {
  [NAME]: "Yik Kok",
  [WEBSITE]: "www.yikkok.com"
}

We can do it this way when using variable as the JSON’s key

So, what is it gonna do with React Native?

Well, this is because recently I’m figuring how to directly access specific styling from props in React Native – not by the style props, I know this could be done easily with just extend the props.

**(Yes, there’s tradeoff for this. So, I will limited the usage and apply to wherever make sense.)

Before I continue, let have a look for the demo video first.

It’s an ordinary updating text styling when the specific button was clicked. Under the scene, there is no if...else, no ? : (ternary statement) involved.

Let’s see the code.

import React, {useState} from 'react';
import {StyleSheet, Text, View, Button, SafeAreaView} from 'react-native';

const STATUS_NORMAL = 'Normal';
const STATUS_WARNING = 'Warning';
const STATUS_ERROR = 'Error';

const statusDescription = {
  [STATUS_NORMAL]: 'All Green.',
  [STATUS_WARNING]: 'Beware of Warning!',
  [STATUS_ERROR]: 'Error, Error!!!',
};
const App: () => React$Node = props => {
  const [status, setStatus] = useState(STATUS_NORMAL);

  function handleOnChangeStatus(newStatus) {
    return () => {
      setStatus(newStatus);
    };
  }

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles[status]}>{statusDescription[status]}</Text>

      <View>
        <Button
          title={STATUS_NORMAL}
          onPress={handleOnChangeStatus(STATUS_NORMAL)}
        />
        <Button
          title={STATUS_WARNING}
          onPress={handleOnChangeStatus(STATUS_WARNING)}
        />
        <Button
          title={STATUS_ERROR}
          onPress={handleOnChangeStatus(STATUS_ERROR)}
        />
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'space-around',
    padding: 20,
  },
  [STATUS_NORMAL]: {
    color: 'green',
  },
  [STATUS_WARNING]: {
    color: 'yellow',
    backgroundColor: 'black',
  },
  [STATUS_ERROR]: {
    color: 'red',
  },
});

export default App;

As we can see from the code. There is no if...else clause and no hardcoded string in the component tree. (I’m not saying that we should eliminate all hardcoded string from component tree. In some cases, it’s easy if you hardcoded it instead of using a variable)

Let’s get back to the code. Firstly, I have three variable indicating the status.

const STATUS_NORMAL = 'Normal';
const STATUS_WARNING = 'Warning';
const STATUS_ERROR = 'Error';

Then, I have two JSON – one is the statusDescription and another one is the styles that created using React Native’s StyleSheet API.

const statusDescription = {
  [STATUS_NORMAL]: 'All Green.',
  [STATUS_WARNING]: 'Beware of Warning!',
  [STATUS_ERROR]: 'Error, Error!!!',
};

and

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'space-around',
    padding: 20,
  },
  [STATUS_NORMAL]: {
    color: 'green',
  },
  [STATUS_WARNING]: {
    color: 'yellow',
    backgroundColor: 'black',
  },
  [STATUS_ERROR]: {
    color: 'red',
  },
});

Now, the function – a closure that will pass the variables for update new status.

function handleOnChangeStatus(newStatus) {
  return () => {
    setStatus(newStatus);
  };
}

// e.g
<Button
  title={STATUS_NORMAL}
  onPress={handleOnChangeStatus(STATUS_NORMAL)}
/>

So, now whenever the status get updated, The content will updated accordingly to the references in JSON. For styling as well.

But why ?

Why put it in variable instead of string as the JSON key since both of them have the same purpose ? Hmmm, there is no specific rules to do it this way.

I found them useful to me is because of following reasons:

  1. Eslint plugins help me detect undefined variable but not string or JSON’s key.
    • Which allow me to do early fails detection.
  2. I’m a human, who will make mistake in my life, including typo… most of the time, this gonna take me a lot of time to debug or trace it.
  3. I heavy rely on the IntelliSense feature provided by Editor/IDE where they show me which variable match my need but not string.
  4. I’m lack of the ability to give everything a name and still able to recall them correctly, so put it in variable can help me prevent the duplication key issue.

Just some thought

This is inspire by a recent engineering blogpost from facebook. Where they utilise the SQLite to driven their UI. So, in my free time, I will try out experiment whether it could be done with the combination of JSON, variables and database to render UI in React Native.

Thank you for reading.  😁

Comments

(0 Comments)

Your email address will not be published. Required fields are marked *