Today I Learned

A Hashrocket project

3 posts by ryanmessner

Use Decorators for React Higher Order Components

When working with React libraries that make use of higher order components, you wrap your component in a function:

import { withRouter } from 'react-router-dom';

class MyComponent extends Component {
  ...
}

export default withRouter(MyComponent)

When chaining through multiple HOC’s, this can become unwieldly:

import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

class MyComponent extends Component {
  ...
}

function mapStateToProps(state) { ... };

export default withRouter(connect(mapStateToProps)(MyComponent));

But there is hope, with the decorator syntax in ES6/Babel you can make this look a bit cleaner:

import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';

function mapStateToProps(state) { ... };

@withRouter
@connect(mapStateToProps)
export default class MyComponent extends Component {
  ...
}

Full documentation here.

Alternate names in destructuring assignment

Want to use destructuring assignment, but don’t like the names of the variables as they exist in the object?

If you have data like this:

const optimus = { name: 'Optimus', type: 'Semi-Truck' };
const bumblebee = { name: 'Bumblebee', type: 'Small Car' };

Instead of creating customized variables like this:

const { name, type } = bumblebee;
const bumblebeeName = name;
const bumblebeeType = type;

You can express this type of destructuring in one line like:

const { name: optimusName, type: optimusType } = optimus;