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


Alexander
Ivlev

Frontend Developer at JetRockets

Explore more of JetRockets