Today I Learned

A Hashrocket project

18 posts by gabrielreis @greis

Invisible components in React Native

Sometimes you want a component to be rendered but not visible to the user and in React Native 0.42 and below, you could accomplish that by setting the component's height and width to 0.

The good news is that React Native 0.43 will make it easier and introduce the CSS property you are already familiar with: display: 'none'.

You can already try it installing the pre-release version 0.43.0-rc.4.

Making your JS files prettier on Vim

We all use VIM at Hashrocket and we can run prettier everytime we save a JS file:

yarn global add prettier
autocmd FileType javascript set formatprg=prettier\ --single-quote\ --trailing-comma\ es5\ --stdin
autocmd BufWritePre *.js :normal gggqG
autocmd BufWritePre *.js exe "normal! gggqG\<C-o>\<C-o>"

And yes. I like trailing comma,

**** Update: There is an open issue on Github when prettier fails to parse the JS file but there is a workaround for it.

Render multiple child components in React

No need to wrap children in a container component anymore. React Fiber will allow you to return more than one child component:

render() {
  return [
    <Child1>,
    <Child2>
  ]
}

http://isfiberreadyyet.com/

Log React Native HTTP calls on Chrome dev tools

There is a workaround to log all React Native HTTP Api calls on the Chrome dev tools. Add the following code to the index files:

if (__DEV__) {
  GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest;
}

Make sure it only works for the dev enviroment checking the __DEV__ variable.

Credits: https://github.com/facebook/react-native/issues/934

Use object spread operator to get remaining values

const props = { width: 10, height: 10, color: 'red' }
const { width, ...rest } = props

// width => 10
// rest => { height: 10, color: 'red' }

Absolute fill component in React Native

If you see yourself repeating this over and over:

const styles = StyleSheet.create({
  backgroundImage: {
    position: 'absolute',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
  },
})

Replace it with:

const styles = StyleSheet.create({
  backgroundImage: {
    ...StyleSheet.absoluteFillObject,
  },
})

How to define a hash object in GraphQL

If your model has a json field or a serialized hash that you want to expose as a ObjectType, just specify the hash_key for each field:

UserPreferenceType = GraphQL::ObjectType.define do
  field :name, types.String, hash_key: 'name'
  field :value, types.String, hash_key: 'value'
end

Use UUID as primary key on Rails with Postgres

Just enable the uuid-ossp extension and set the id field with uuid:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    enable_extension 'uuid-ossp'
    create_table :users, id: :uuid do |t|
      t.string :name
      t.timestamps
    end
  end
end

Pipe | after | grep

The grep command may not work properly if you want to pipe another command after it, specially when you are tailing a file for example. Just call grep with --line-buffered

heroku logs -t | grep --line-buffered "heroku\[router\]" | awk '{print $11" "$5}'

This command outputs an easy-to-read performance log for each HTTP request:

service=266ms path="/api/posts"
service=142ms path="/api/users"

Compare semantic versions in Ruby

Gem::Version.new('1.0.1') > Gem::Version.new('1.0')

How to Render Base64 Encoded Image on React Native

Just use data URI scheme same as you would in html:

const encodedData = 'R0lGODlhAQABAIAAAAAA...7';
<Image source={{uri: `data:image/gif;base64,${encodedData}`}} />

List local branches sorted by most recent commit

If you have a lot of local branches in your repo and you want to sort them by most recent commits:

git for-each-ref --sort=-committerdate refs/heads/

Source

TouchableHighlight with custom component

Usually in React Native when you want to add touch events to a custom component you just wrap it with a Touchable* component.

If you want to use TouchableOpacity there is no need to change anything on the custom component, but if you want to use TouchableHighlight you have to change the component and implement setNativeProps and delegate to the container View:

class CustomComponent extends Component {
  render() {
    return (
      <View ref='container'>
        ...
      </View>
    )
  }

  setNativeProps(nativeProps) {
    this.refs.container.setNativeProps(nativeProps);
  }
}

And then you are ready to go:

<TouchableHighlight onPress={this._onPress} underlayColor="#fc0">
  <CustomComponent />
</TouchableHighlight>

Manually dismiss keyboard on React Native

To manually dismiss the keyboard just use the dismissKeyboard function:

const dismissKeyboard = require('dismissKeyboard');

_onSomethingElse() {
  dismissKeyboard();
}

Hot Reloading Error on React Native 0.22

If you upgrade your React Native app to 0.22 and you start getting the following error <Text> can't have any children except <Text>, <Image> or raw strings even if your <Text> components are all correct, just disable the new Hot Reloading feature that was introduced in this version and the errors will stop:

Shake the device => Disable Hot Reloading

Linear Gradient in React Native

So far, there is no official implementation for linear gradients in React Native but there is a really cool open source component that implements that for both platforms: Android and iOS.

Check it out react-native-linear-gradient

<LinearGradient
  colors={['#F00', 'transparent']}
/>

Clip subviews content out of bounds

In iOS when you want to clip part of the subviews that are out of the bounds you just set clipsToBounds = YES; in the parent view.

In Android you set setClipChildren(true); in the ViewGroup.

React Native tries to mimic CSS with their own implementation of it, so you can set the property overflow: 'hidden' in the view's style.

Easy as pie!

Push specific commit to remote repo

Sometimes you have multiple local commits and you want to push just part of them to the remote repo. Just specify the SHA1 for the revision you want and everything below it will be pushed.

git push <remote> <SHA1>:<branch>