Member-only story
React-Rails — Snake or Camel ?
When working on React projects it’s standard convention to use camelCase and in Rails use snake_case. So, when using Rails as a backend for a React frontend project — do you use snake_case or camelCase?
I have experimented with all sorts of ways of handling this frontend-backend communication. One option is to ignore the convention in the backend and create our model columns using camelCase. That way, there’s no need for conversion upon receiving or sending information. However, this is against the standard convention and can be a little confusing when the rest of your variables and methods are snake_case.
Option two is to use snake_case in the parts of our frontend that get sent to the backend. Although, we reach the same problem as option 1. It can both be confusing and is against convention.
So…now what? If we’re not going to compromise convention on either of them — how can the front and backend communicate with each other?
That’s where Humps comes in. Humps is a Javascript library that can convert keys of objects into snake_case or camelCase. For example, camelizeKeys({first_name: ‘John’, last_name: ‘Doe’})
would return {firstName: ‘John’, lastName: ‘Doe’}
. The same is true in reverse — decamelizeKeys({firstName: ‘John’, lastName: ‘Doe’})
would return {first_name
…