Small Javascript & React tricks I've been using

March 3, 2021
views 3 min read

Been a developer and designer for 14 years now, and it's crazy what we can do with JS nowadays. I've been using some Javascript and React tricks lately and I think you'll love these.

Conditional object keys

As an example, imagine we have a getProfile function that will receive a social object, as an example:

social = {
  twitter: {
    handler: '@telmo'
  },
  github: {
    username: 'telmogoncalves'
  }
}

Now, I only want to return both twitter or github if they exist, lets take a look of what I like to call the old way:

const getProfile = (social) => {
  let data = {}

  if (social.twitter) {
    data.twitter = social
  }

  if (social.github) {
    data.github = social
  }

  return data
}

This is totally fine and it works perfectly, although it can start looking a little messed up. What I've been using lately looks much cleaner in my opinion:

// I'm destructuring our data here, we can also do this
// in the previous example.
const getProfile = ({ twitter, github }) => ({
  ...twitter && { twitter },
  ...github && { github },
})

Javascript Dictionary

I'll be using a React component example on this one. Lets look into the followin example:

function Component({ name, state }) {
  return (
    <div>
      Hello {name}
    </div>
  )
}

Now, imagine state can be MORNING, AFTERNOON or NIGHT. We want to display different styles and a different content depending on that state:

function Component({ name, state }) {
  let style, content

  if (state === 'MORNING') {
    style = { color: 'yellow' }
    content = 'Top of the morning'
  } else if (state === 'AFTERNOON') {
    style = { color: 'orange' }
    content = 'Wow, afternoon'
  } else if (state === 'NIGHT') {
    style = { color: 'darkblue' }
    content = 'Sleep tight'
  }

  return (
    <div style={style}>
      {content} {name}
    </div>
  )
}

Once again, this is totally fine and it works perfectly. Although I believe there are better ways to handle this. Specially once the component starts go get a little more complex:

function Component({ name, state }) {
  const details = {
    MORNING: {
      style: { color: 'yellow' },
      content: 'Top of the morning',
    },
    AFTERNOON: {
      style: { color: 'orange' },
      content: 'Wow, afternoon',
    },
    NIGHT: {
      style: { color: 'darkblue' },
      content: 'Sleep tight',
    }
  }

  const { style, content } = details[state]

  return (
    <div style={style}>
      {content} {name}
    </div>
  )
}

Although it might look similar, it's way more cleaner in my opinion, also feels easier to add more states if we want.

Yeah yeah, I know instead of the ifs I could use while, I still feel using a Javascript dictionary is much cleaner, purely personal opinion.

Read next
Millionaires vs. Billionaires
October 17, 2021
views