• Stars
    star
    138
  • Rank 264,508 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Allows you to code using certain React.next features today! Perfect for component library maintainers.

react-af

Build Status npm version

React AF graffiti wall

TL;DR

  • Allows you to code using certain React.next features today!
  • Perfect for component library maintainers.
  • It does for React what Babel does for JavaScript.
  • Support getDerivedStateFromProps on older versions of React.
  • Supports Fragment on older versions of React.
  • Supports createContext (the new context API) on older versions of React.

What is this project?

Starting with React 17, several class component lifecycles will be deprecated: componentWillMount, componentWillReceiveProps, and componentWillUpdate (see React RFC 6).

One problem that React component library developers face is that they don't control the version of React that they run on — this is controlled by the consuming application. This leaves library developers in a bit of a quandary. Should they use feature detection or code to the lowest denominator?

react-af emulates newer features of React on older versions, allowing developers to concentrate on the business problem and not the environment.

Install

Install react-af using npm:

$ npm install react-af --save

or with Yarn:

$ yarn add react-af

Import

In your code, all you need to do is change the React import from this:

import React from 'react';

To this:

import React from 'react-af';

That's it! You can now code your library components as though they are running on a modern React (not all features supported... yet), even though your code may be running on an older version.

react-af imports from react under the hood (it has a peerDependency of React >=15), patching or passing through features where necessary.

API

Here are the modern React features that you can use, even if yur code is running on older version of React 15 or React 16.

getDerivedStateFromProps

react-af supports new static lifecycle getDerivedStateFromProps.

Here is an example component written using componentWillReceiveProps.

class ExampleComponent extends React.Component {
  state = { text: this.props.text };

  componentWillReceiveProps(nextProps) {
    if (this.props.text !== nextProps.text) {
      this.setState({
        text: nextProps.text
      });
    }
  }
}

And here it is after converting to be compatible with modern React.

class ExampleComponent extends React.Component {
  state = {};

  static getDerivedStateFromProps(nextProps, prevState) {
    return prevState.text !== nextProps.text
      ? {
        text: nextProps.text
      }
      : null;
  }
}

Fragment

Starting with React 16.2, there is a new <Fragment /> component that allows you to return multiple children. Prior to 16.2, you needed to wrap multiple children in a wrapping div.

With react-af, you can use React.Fragment on older versions of React as well.

import React, { Fragment } from 'react-af';

const Weather = ({ city, degrees }) => (
  <Fragment>
    <div>{city}</div>
    <div>{degrees}</div>
  </Fragment>
);

The code above works natively in React 16.2 and greater. In lesser versions of React, Fragment is replaced with a div automatically.

createContext

React 16.3 also added support for the new context API. Well react-af supports that as well.

Here's an example take from Kent Dodds's article React’s new Context API.

import React, { createContext, Component } from 'react-af';

const ThemeContext = createContext('light')
class ThemeProvider extends Component {
  state = {theme: 'light'}
  render() {
    return (
      <ThemeContext.Provider value={this.state.theme}>
        {this.props.children}
      </ThemeContext.Provider>
    )
  }
}
class App extends Component {
  render() {
    return (
      <ThemeProvider>
        <ThemeContext.Consumer>
          {val => <div>{val}</div>}
        </ThemeContext.Consumer>
      </ThemeProvider>
    )
  }
}

Other projects

react-lifecycles-compat

You might also want to take a look at react-lifecycles-compat by the React team. It doesn't support Fragment or createContext and it requires additional plumbing to setup, but it's lighter and may be adequate for some projets.

create-react-context

If all you need is context support, consider using create-react-context, which is what this package uses to emulate createContext().

What's with the name?

ReactAF stands for React Always Fresh (or React As F&#%!). Your choice.

More Repositories

1

hook-flow

A flowchart that explains the new lifecycle of a Hooks component. https://dwe.st/hf
Shell
2,157
star
2

use-persisted-state

A custom React Hook that provides a multi-instance, multi-tab/browser shared and persistent state.
JavaScript
1,378
star
3

use-dark-mode

A custom React Hook to help you implement a "dark mode" component.
JavaScript
1,288
star
4

use-event-listener

A custom React Hook that provides a declarative useEventListener
JavaScript
356
star
5

thwack

A tiny modern data fetching solution
JavaScript
269
star
6

undefined-is-a-function

"undefined is not a function"? — It is now!
JavaScript
241
star
7

use-interval

A custom React Hook that provides a declarative setInterval called useInterval.
TypeScript
161
star
8

styled-shortcuts

Provides convenient props shortcut helper for Styled Components 💅
JavaScript
88
star
9

superjson-remix

TypeScript
84
star
10

render-props

Easily and reliably support Render Props, Component Injection, and Function as a Child
JavaScript
83
star
11

use-firebase-auth

A custom React Hook that provides a declarative interface for Firebase Auth.
JavaScript
78
star
12

remix-etag

HTML
70
star
13

use-instance

A custom React Hook that provides a sensible alternative to useRef for storing instance variables.
TypeScript
38
star
14

use-visibility-change

Know how long it's been since a user has "seen" your app.
TypeScript
33
star
15

big-sur-icons

A collection of re-imagined icons for popular apps in the macOS Big Sir style
24
star
16

reclass

Write React stateful components without worrying about this or binding methods.
JavaScript
24
star
17

transformer-open-graph

TypeScript
23
star
18

splashr

A React component that takes the effort out of adding a Splash Screen to your web application.
JavaScript
21
star
19

react-router-relative-link

Allows react-router's Link component to accept relative paths.
JavaScript
19
star
20

use-firebase-app

JavaScript
17
star
21

json_

Converts camelCase JavaScript objects to JSON snake_case and vise versa.
TypeScript
17
star
22

use-prev-prop

A custom React Hook that maintains a previous value for a prop (or any other value).
JavaScript
16
star
23

lambdog-server

Write Netlify functions without pulling your hair out.
JavaScript
15
star
24

use-firebase-database

JavaScript
14
star
25

styled-units

You might want to try https://github.com/donavon/styled-shortcuts instead
JavaScript
14
star
26

styled-shortcut-components

A convenience package that wraps styled-components with styled-shortcuts.
JavaScript
13
star
27

init-readme

An opinionated README.md generator for npm utility packages
JavaScript
12
star
28

garage-door

JavaScript
12
star
29

hrd

An npx utility to make it easy to hoard, um… reserve an npm name.
Shell
10
star
30

use-pdf

TypeScript
9
star
31

intl-parse-accept-language

TypeScript
8
star
32

lloop

A React JSX Loop component with the lloopy name
JavaScript
6
star
33

xcop

An XHR Cross Origin Proxy
JavaScript
5
star
34

react-proxy-hook

Helps you test a React Hook
JavaScript
5
star
35

use-cached-state

JavaScript
5
star
36

binclock

A binary clock written in React using TypeScript
TypeScript
4
star
37

remix-patches

4
star
38

donavon

3
star
39

react-extended-render

Extends React's `Component` by passing `props`, `state`, and `context` to the `render` method of a class.
JavaScript
3
star
40

render-fragment

JavaScript
3
star
41

consoleit

Utility to append console messages to the DOM. Useful when using RequireBin, JSFiddle, or the like.
JavaScript
3
star
42

Star-Wars-Episode-I-The-Phantom-Menace

Script for "Star Wars: Episode I – The Phantom Menace" entirely using git commit messages. Like it? Give it a ⭐️ on GitHub.
3
star
43

use-step-multi-step-form-demo

Created with CodeSandbox
JavaScript
3
star
44

crapp-ts

An npx utility to run create-react-app with the TypeScript template.
Shell
3
star
45

animated-placeholder

JavaScript
2
star
46

lambdog-client

JavaScript
2
star
47

spreadlove.io

HTML
2
star
48

react-wobbly-spinner

A Wobbly Spinner Component for React
JavaScript
2
star
49

multi-cookie-session

TypeScript
2
star
50

chime-devices

This package contains a React context provider and a hook around AWS Chime for capturing system audio and video devices.
TypeScript
1
star
51

build-uri-path

Reliably build a Uri path
JavaScript
1
star
52

resume

1
star
53

prevent-default

A wrapper that calls `event.preventDefault()` for you.
JavaScript
1
star
54

render-array

JavaScript
1
star
55

netlify-faunadb-example

JavaScript
1
star
56

thwack-resolve

A tiny functional equivalent to` new URL(url, base).href`
TypeScript
1
star
57

babel-plugin-transform-class-private-properties

A Babel transform to convert pseudo-private "underscore convention" private class properties to truly private properties.
1
star