Today I Learned

A Hashrocket project

10 posts about #react

Handle JS Errors in React 16

React 16 introduced a new method called componentDidCatch to catch all JS errors. It can catch errors during rendering, lifecycle methods and constructors of the whole tree below.

class App extends React.Component {

  componentDidCatch(error, info) {
    ErrorService.log(error, info);
  }

  render() {
     // code that raises error, it could come from this component or its children.
  }
}

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.

React wrapper components with nested children

Say you want to create a component that acts as a wrapper such that you can pass it nested child components like so:

<WrapperComponent title="I am the wrapper">
  <ChildComponent body="Hello from child component" />
</WrapperComponent>

This can be achieved by using this.props.children as in this example:

class WrapperComponent extends Component {
  render() {
    return (
      <div className="wrapper">
        <h1>{this.props.title}</h1>
        {this.props.children}
      </div>
    );
  }
}

class ChildComponent extends Component {
  render() {
    return (
      <p>{this.props.body}</p>
    );
  }
}

class App extends Component {
  render() {
    return (
      <WrapperComponent title="I am the wrapper">
        <ChildComponent body="Hello from child component" />
      </WrapperComponent>
    );
  }
}

Mounting App will produce the following markup:

<div class="wrapper">
  <h1>I am the wrapper</h1>
  <p>Hello from child component</p>
</div>

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>