Today I Learned

This project exists to catalogue the sharing & accumulation of knowledge as it happens day-to-day. Posts have a 200-word limit, and posting is open to any Rocketeer as well as selected friends of JetRockets. We hope you enjoy learning along with us.

2 posts by Alexander Ivlev @atamurana

Recompose withContext and getContext. Simple example

Very often for nested components you need to transfer some props of the parent. For example size. So, we have the Card component. It contains a Button component.

  // App.js
  <Card size="sm">
    {/* ... */}
    <div>
      {/* ... */}
      <Button size="sm" onClick={action}>Action</Button>
    </div>
  </Card>

The size for both components is set by the “size” parameter. In the example above, the parameter passed is indicated for both components. In order not to specify the size for the Button each time, you can use the Context to use the one specified for the Card. If you use recompose, it can be super easy:

  // Card.js
  import { getContext } from 'recompose';
  // ...
  export default withContext(
    { size: PropTypes.oneOf(['sm', 'md', 'lg']) },
    ({ size }) => ({ size }),
  )(Card);
  
  // App.js
  import Button from './Button';
  // ...
  const EnhancedButton = getContext({ size: PropTypes.oneOf(['sm', 'md', 'lg']) })(Button);

Live example

Sort lines in the vim editor

Often when writing code, you need to sort the lines in alphabetical order. For example, in javascript, when importing a large number of modules, it is good practice to organize them alphabetically. Users of the vim editor can do this very simply. It is enough to select in the visual mode all the lines that need to be sorted and enter the command :sort. All rows are sorted!