Coder Social home page Coder Social logo

react-renderless's Introduction

react-renderless ๐Ÿ–‡

Utilities for creating and working with renderless React components.

What is a "renderless component"? A renderless component is the opposite of a stateless component. It does not implement a render method. Instead, renderless components are composed with stateless functional components to create UI elements.

Usage

Script

<script src="https://unpkg.com/react-renderless"></script>
const { StateProvider, withRender } = reactRenderless

Package

yarn add react-renderless
# OR
npm install --save react-renderless
// commonjs
const { StateProvider, withRender } = require("react-renderless") 
// es module
import { StateProvider, withRender } from "react-renderless" 

API

StateProvider Component

Instead of extending React.Component for renderless components, extend StateProvider.

StateProvider.propTypes = {
  children: PropTypes.func, // pass either children or render
  render: PropTypes.func, // pass either children or render
  initialState: PropTypes.object, // optional
}
  • The render prop will be called with 2 arguments: (props, context) where props is {...this.props, ...this.state, ...this.handlers}. The prop should either be render or the only child of the parent. The render prop must return an element when called (not a component class)!

  • Initial state: The component's initial state can be set by passing a prop or by setting an initialState getter on the class.

  • Handlers: An object that provides all the actions needed to modify the state. It is initiated one time, at mount. Handlers that need to be bound to the component instance should use arrow functions for declaration. (This will not create additional functions in each render.)

class SimpleState extends StateProvider {
  get initialState() {
    return {
      foo: "bar",
    };
  }

  get handlers() {
    return {
      set: (key, value) => this.setState({ [key]: value }),
    };
  }
}

const App = () => (
  <SimpleState
    render={({foo}) => <b>{foo}</b>}
    initialState={{foo: 'baz'}}
  />
)

// renders "baz" because the initialState prop overrides the getter

withRender Higher-Order Component

withRender combines a container and presenter (renderless and stateless) into a new component that acts like a normal React component. Under the hood it simply passes the presenter as the render prop to the renderless component.

const Combined = withRender(MyStateProvider, MyRenderFunction)

const App = () => <Combined initialState={{foo: 'baz'}} />

withRender is curried so it can either be with 1 argument to create a factory for a stateful component or 2 to create a new component immediately.

const textStateFactory = withRender(TextState)
const TextInput = textStateFactory(Input)
const BigTextInput = textStateFactory(BigInput)

Examples

Textboxes Codepen

screen shot 2017-09-28 at 1 14 30 am

const Input = ({ text, setText }) => <input onChange={setText} value={text} />;

class Text extends StateProvider {
  get handlers() {
    return {
      setText: e => this.setState({ text: e.target.value })
    };
  }
}

class UpperText extends StateProvider {
  get initialState() {
    return {
      text: ""
    };
  }

  get handlers() {
    return {
      setText: e => this.setState({ text: e.target.value.toUpperCase() })
    };
  }
}

class LowerText extends StateProvider {
  get handlers() {
    return {
      setText: e => this.setState({ text: e.target.value.toLowerCase() })
    };
  }
}

const TextInput = props => <Text {...props}>{Input}</Text>;
const UpperTextInput = withRender(UpperText, Input);

const App = () => (
  <div>
    <TextInput initialState={{ text: "" }} /> TextInput <br />
    <UpperTextInput /> UpperTextInput <br />
    <LowerTextInput initialState={{ text: "" }} /> LowerTextInput
  </div>
);

ReactDOM.render(<App />, document.body);

Reducer Codepen

screen shot 2017-09-28 at 2 39 14 am

class Reducer extends StateProvider {
  get handlers() {
    const reducer = {
      "foo:update": ({ foo }) => ({ foo: foo }),
      "bar:inc": () => ({ bar: this.state.bar + 1 }),
      "bar:dec": () => ({ bar: this.state.bar - 1 })
    };
    return {
      action: (type, payload) => {
        if (!reducer[type]) this.setState({});
        this.setState(reducer[type](payload));
      }
    };
  }
}

const App = () => (
  <Reducer initialState={{ foo: "", bar: 0 }}>
    {({ action, ...state }) => (
      <div>
        <p>
          <b>Foo</b>&nbsp;
          <input
            onChange={e => action("foo:update", e.target.value)}
            value={state.foo}
          />
        </p>
        <p>
          <b>Bar</b>&nbsp;
          <button onClick={() => action("bar:dec")}>+</button>
          <span>{state.bar}</span>
          <button onClick={() => action("bar:inc")}>+</button>
        </p>
      </div>
    )}
  </Reducer>
);

ReactDOM.render(<App />, document.body);

Inspiration

License

MIT

react-renderless's People

Contributors

alexkrolick avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.