Code Monkey home page Code Monkey logo

component's Introduction

Reactions Component

This has moved to Reach UI, but this repo is here for the sake of history I guess.

What?

Declarative version of React.Component.

Why?

Because sometimes you want a lifecycle or some state but don't want to create a new component. Also, this stuff is composable as heck.

Installation

npm install @reactions/component
# or
yarn add @reactions/component

And then import it:

// using es modules
import Component from "@reactions/component";

// common.js
const Component = require("@reactions/component");

// AMD
// I've forgotten but it should work.

Or use script tags and globals.

<script src="https://unpkg.com/@reactions/component"></script>

And then grab it off the global like so:

const Component = ReactionsComponent;

How?

Let's say you want some async data but don't want to make a whole new component just for the lifecycles to get it:

// import Component from '@reactions/component'
const Component = ReactComponentComponent;

ReactDOM.render(
  <div>
    <h2>Let's get some gists!</h2>
    <Component
      initialState={{ gists: null }}
      didMount={({ setState }) => {
        fetch("https://api.github.com/gists")
          .then(res => res.json())
          .then(gists => setState({ gists }));
      }}
    >
      {({ state }) =>
        state.gists ? (
          <ul>
            {state.gists.map(gist => (
              <li key={gist.id}>{gist.description}</li>
            ))}
          </ul>
        ) : (
          <div>Loading...</div>
        )
      }
    </Component>
  </div>,
  DOM_NODE
);

Or maybe you need a little bit of state but an entire component seems a bit heavy:

// import Component from '@reactions/component'
const Component = ReactComponentComponent;

ReactDOM.render(
  <Component initialState={{ count: 0 }}>
    {({ setState, state }) => (
      <div>
        <h2>Every app needs a counter!</h2>
        <button
          onClick={() =>
            setState(state => ({ count: state.count - 1 }))
          }
        >
          -
        </button>
        <span> {state.count} </span>
        <button
          onClick={() =>
            setState(state => ({ count: state.count + 1 }))
          }
        >
          +
        </button>
      </div>
    )}
  </Component>,
  DOM_NODE
);

Props

You know all of these already:

  • didMount({ state, setState, props, forceUpdate })
  • shouldUpdate({ state, props, nextProps, nextState })
  • didUpdate({ state, setState, props, forceUpdate, prevProps, prevState })
  • willUnmount({ state, props })
  • children({ state, setState, props, forceUpdate })
  • render({ state, setState, props, forceUpdate })

Legal

Released under MIT license.

Copyright ยฉ 2017-present Ryan Florence

component's People

Contributors

maciekmaciej avatar maxdeviant avatar ryanflorence avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

component's Issues

shouldComponentUpdate using nextProps

I think shouldComponentUpdate should use nextProps instead of props in order to allow this:

<Component shouldUpdate={() => !loading}>

Currently I need to do such a thing:

<Component shouldUpdate={({ nextProps: { loading } }) => !loading} loading={loading}>

Changes are:

shouldComponentUpdate(nextProps, nextState) {
    if (this.nextProps.shouldUpdate)
      return this.nextProps.shouldUpdate({
        props: this.props,
        state: this.state,
        nextProps,
        nextState,
      });
    else return true;
  }

Flow

Would you be ok with adding Flow types? I can create a PR if that's ok ...

didCatch?

seems like its easy enough to include. was leaving it out unintentional? if not am happy to pr

Copypaste issue with invariant Error message

Hello, I just found out about your package thanx to Kent C Dodds email list, and went through the source code.

I found this minor issue, which could be confusing for newcomers.

Have a nice day!

componentWillReceiveProps(nextProps, nextState) {
    invariant(
      !this.props.willReceiveProps,
      "<Component> Please use `didUpdate` instead of `willReceiveProps`."
    );
  }

  componentWillUpdate(nextProps, nextState) {
    invariant(
      !this.props.willUpdate,
      "<Component> Please use `didUpdate` instead of `willReceiveProps`."
    );
  }

"<Component> Please use `didUpdate` instead of `willReceiveProps`."
should be replaced with"<Component> Please use `didUpdate` instead of `willUpdate`."

Removing didMount listeners?

๐Ÿ‘‹ Hi @ryanflorence!

Been enjoying your lib today and found that with libraries that have listeners, because setState are locally accessed, it's difficult to remove them via willUnmount without replacing Component entirely.

For example:

    <GoogleApi>
      {(api) => (
        <Component
          initialState={{
            isSignedIn: api.auth2.getAuthInstance().isSignedIn.get(),
            signIn: api.auth2.getAuthInstance().signIn,
            signOut: api.auth2.getAuthInstance().signOut,
            user: getUserFromAuth(api.auth2.getAuthInstance()),
          }}
          didMount={({ setState }) => {
            // ๐Ÿ‘‡ Because this needs access to `setState`,
            // it's not clear how to best remove this listener via `willUnmount`:
            api.auth2.getAuthInstance().isSignedIn.listen(() => {
              setState({
                isSignedIn: api.auth2.getAuthInstance().isSignedIn.get(),
              })
            })
          }}
        >
          {({ state }) => children(state)}
        </Component>
      )}
    </GoogleApi>

A couple options off the top of my head:

  1. Have setState noop when the component is unmounted. (Fixes warnings from React, but doesn't remove the listener).
  2. User tracks the listener in a local variable (e.g. let listener). (This would have to be hoisted higher & higher out of scope to ensure that parents re-rendering don't blow away the reference).
  3. <Component> methods pass a reference to self or instance for the user to use for storage (e.g. instance.listener = () => setState({ ... })), which would be accessible via willUnmount({ instance }). (Maybe this could also be useful ReactDOM.findDOMNode(instance), too?)
  4. didMount can return [...listeners] which would be accessible via willUnmount(props, ...listeners) as an argument for cleanup.
  5. Store listeners in state. ๐Ÿคทโ€โ™€๏ธ
  6. Something else because I gotta go :)

Do you recommend using this with callback refs?

Is there a recommended way to set and access a ref as done in a regular component as follows (using callback ref)? I want to make a lightweight component that can get the dimensions of the ref node in didMount. I'm assuming I need to just create a 'normal' component :).

class MyComponent extends Component {
  componentDidMount() {
    this.something.scrollIntoView();
  }

  render() {
    return (
      <div>
        <div ref={node => this.something = node} />
      </div>
    )
  }
}

Include forceUpdate in shouldUpdate()

We sometimes want to write the shouldComponentUpdate() function like this:

shouldComponentUpdate() {
    requestAnimationFrame(this.forceUpdate.bind(this));
    return false;
}

So maybe a reference to the forceUpdate method should be passed to the shouldUpdate property, or why is this approach wrong?

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.