1.0.0 • Published 6 years ago

wrap-if v1.0.0

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

wrap-if

Conditional Element wrapping

NPM JavaScript Style Guide

Install

npm install --save wrap-if

Usage

There are 2 exported functions:

  • wrapIf(Wrapper)(elemOrFn)(predicate)
  • ifThenWrap(predicate)(Wrapper)(elemOrFn)

WrapIf

This curried HoF allows for simpler and more declarative element wrapping. Instead of doing something like:

import React, { Component } from 'react'
import {wrapIf} from 'wrap-if'

const Wrapper = (props) => <div className="wrapper">I wrap: {props.children}</div>
const Child = () => <div>I sometimes get wrapped</div>

class Example extends Component {
  render () {
    const shouldWrap = true;
    return (
      {shouldWrap ? (<Wrapper><Child /></Wrapper>) : (<Child />)}
    )
  }
}

One now can declare those components beforehand and then render later on without any of the inline code needed.

import React, { Component } from 'react'
import {wrapIf} from 'wrap-if'

const Wrapper = (props) => <div className="wrapper">I wrap: {props.children}</div>
const maybeWrapped = wrapIf(Wrapper)(<div>I sometimes get wrapped</div>)

class Example extends Component {
  render () {
    const Wrapped = maybeWrapped(true);
    const NonWrapped = maybeWrapped(false);
    return (
      <Wrapped />
      <NonWrapped />
    )
  }
}

ifThenWrap

This function is useful in cases where one would want to create their own Wrappers, but only conditionally.

License

MIT © jutaz