Coder Social home page Coder Social logo

react-lifecycles-compat's Introduction

react-lifecycles-compat

What is this project?

React version 17 will deprecate several of the class component API lifecycles: componentWillMount, componentWillReceiveProps, and componentWillUpdate. (Read the Update on Async rendering blog post to learn more about why.) A couple of new lifecycles are also being added to better support async rendering mode.

Typically, this type of change would require third party libraries to release a new major version in order to adhere to semver. However, the react-lifecycles-compat polyfill offers a way to use the new lifecycles with older versions of React as well (0.14.9+) so no breaking release is required. This enables shared libraries to support both older and newer versions of React simultaneously.

How can I use the polyfill

First, install the polyfill from NPM:

# Yarn
yarn add react-lifecycles-compat

# NPM
npm install react-lifecycles-compat --save

Next, update your component and replace any of the deprecated lifecycles with new ones introduced with React 16.3. (Refer to the React docs for examples of how to use the new lifecycles.)

Lastly, use the polyfill to make the new lifecycles work with older versions of React:

import React from 'react';
import {polyfill} from 'react-lifecycles-compat';

class ExampleComponent extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Normally this method would only work for React 16.3 and newer,
    // But the polyfill will make it work for older versions also!
  }

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Normally this method would only work for React 16.3 and newer,
    // But the polyfill will make it work for older versions also!
  }

  // render() and other methods ...
}

// Polyfill your component so the new lifecycles will work with older versions of React:
polyfill(ExampleComponent);

export default ExampleComponent;

Which lifecycles are supported?

Currently, this polyfill supports static getDerivedStateFromProps and getSnapshotBeforeUpdate- both introduced in version 16.3.

Validation

Note that in order for the polyfill to work, none of the following lifecycles can be defined by your component: componentWillMount, componentWillReceiveProps, or componentWillUpdate.

Note also that if your component contains getSnapshotBeforeUpdate, componentDidUpdate must be defined as well.

An error will be thrown if any of the above conditions are not met.

react-lifecycles-compat's People

Contributors

aladin002dz avatar andarist avatar asantarissy avatar billyjanitsch avatar bvaughn avatar dependabot[bot] avatar gaearon avatar hypnosphi avatar yesmeck avatar zombiej 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  avatar  avatar

react-lifecycles-compat's Issues

License not version-tagged

Dear React-Team and @bvaughn,

thanks a lot for your awesome work and everything you've done for the web!

We would like to use react-virtualized, but we're required to list a license that is specifically tagged to the version that we're using. Since this package is a subdependency of react-virtualized, this also applies to this package. Unfortunately, there aren't any github releases or version tags on this repository which doesn't allow us to use it - it would be awesome if you could add a version tag!

Thanks in advance!

Cheers,
Felix

Polyfill UNSAFE_* aliases

Per the blog post, React 16.3 will

Introduce aliases for the unsafe lifecycles, UNSAFE_componentWillMount, UNSAFE_componentWillReceiveProps, and UNSAFE_componentWillUpdate.

Is there an intention to polyfill these aliases here?

Test case failure while building react-lifecycles-compat on PowerPC64LE - ppc64le

Trying the build using npm install, getting the following test case failure while building react-lifecycles-compat on PowerPC64LE - ppc64le:-

index.js → react-lifecycles-compat.min.js...
created react-lifecycles-compat.min.js in 202ms

> [email protected] test /home/tester/react-lifecycles-compat
> jest test.js

 FAIL  ./test.js
  ● Test suite failed to run

    SecurityError: localStorage is not available for opaque origins

      at Window.get localStorage [as localStorage] (node_modules/jsdom/lib/jsdom/browser/Window.js:257:15)
          at Array.forEach (<anonymous>)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.815s
Ran all test suites matching /test.js/i.
npm ERR! Test failed.  See above for more details.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prepublish: `npm test`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prepublish script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-04-10T10_32_03_767Z-debug.log

Any help would be greatly appreciated.

`getDerivedStateFromProps` not called before each `render`

Hi,
I wrote a component Switch: https://codesandbox.io/s/m5oy50k649

When I use React and [email protected], getDerivedStateFromProps will be called everytime before the render method.
image

but when I use React and [email protected], and with this polyfill, getDerivedStateFromProps is called just before the first render, as my example shows. This is not what I expected.
image

React Doc:

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates

Here's what I want:
Switch has a state checked, and a prop checked as well.
if <Switch />, the component can work because it has it's own state checked;
if <Switch checked />, the component will never change state, because before every render, getDerivedStateFromProps will reset the components' checked.

But when React and [email protected], It doesn't work as I expected.

Thanks for helping.

IE 10 support

When running our react project in IE10 I get this error in the console and component doesn't load

"Can only polyfill class components"

Doesn't demand `null` be returned

The current implementation of getDerivedStateFromProps() polyfill is not fully correct: it doesn't demand null be returned which is required by the official spec.

function componentWillReceiveProps(nextProps) {
  // Call this.constructor.gDSFP to support sub-classes.
  var state = this.constructor.getDerivedStateFromProps(nextProps, this.state);
  if (state !== null && state !== undefined) {
    this.setState(state);
  }
}

Instead it should be:

  ...
  if (state !== null && state !== undefined) {
    this.setState(state);
  }
  if (state === undefined) {
    console.warn('Warning: getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.');
  }
}

Failed to minify the code from this file: react-lifecycles-compat.es.js:64

Hello,

I'm using react-scripts to generate a build production to deploy my application, and on the build step throws this error:

Failed to minify the code from this file:
        ./node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js:64

Have any chance to help investigate what in this file might be causing the minification failure?

As a hot fix i've minified manually the file on https://babeljs.io/repl

Perhaps fill that ellipsis in the README with a couple of methods.

People are having difficulties with understanding how the polyfill actually works (what does it actually do).
gpbl/react-day-picker#685

Perhaps the README could be more descriptive about that, something like:

import React from 'react';
import {polyfill} from 'react-lifecycles-compat';

class ExampleComponent extends React.Component {
  getSnapshotBeforeUpdate(prevProps, prevState) { ... }
  static getDerivedStateFromProps(props, state) { ... }
  ...
}

// Polyfill your component so the new lifecycles will work with older versions of React:
polyfill(ExampleComponent);

export default ExampleComponent;

v1.1.4 suddenly not exporting module?

we've been using a lib for some time that requires ^1.0.2, last successful build installed 1.1.4 according to package-lock.json, however it seems the interface has changed? The lib that we're using requires the module, and attempts to invoke polyfill() as a method of the module. This has been successful in the past with 1.1.4, but on current builds, it seems that the default export of the installed version is the polyfill() method itself, which is undefined. I'm really confused about this one, as it seems that npm says the last upload was months ago. Is it possible that the tarball was updated?

StrictMode warnings

If a polyfilled component uses getSnapshotBeforeUpdate but doesn't use static getDerivedStateFromProps, it produces a warning in strict mode:

https://codesandbox.io/s/v6rv7v59l3

Warning: Unsafe lifecycle methods were found within a strict-mode tree:
    in App


componentWillUpdate: Please update the following components to use componentDidUpdate instead: MyComponent

The reason is that React only checks for suppressed warning in cWM, which isn't applied for gSBU
https://github.com/facebook/react/blob/8ec0e4a99df76c0ff1779cac4f2eaaaf35a6b5bb/packages/react-reconciler/src/ReactStrictModeWarnings.js#L244

Add changelog

It's hard to track what are the breaking changes right now

Failed to compile with Create-react-app.

Failed to compile with Create-react-app.

I am using Version 2.0.1 of react-lifecycles-compat

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

    ./node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js:64

Use named export and add ES module to dist

CJS modules can cause tree shaking problems for other packages that use them. It would be nice to provide an ES module version of this project (which should be as easy as uncommenting this line and adding a new entry to the "files" array.

Unfortunately we can't do that without a breaking change, since the current CJS bundle uses an unnamed/default export which we can't mirror with an ES module (without causing problems when required).

I think the most straight forward solution is to use a named export in the next major:

import {polyfill} from 'react-lifecycles-compat';

// or...

const {polyfill} = require('react-lifecycles-compat');

We could add a deprecation warning to the default export only and do one final 1.x release before making this change, to follow a similar upgrade strategy as React uses.

Use react-lifecycles-compat with hoc

Hi!

Looks like we currently we can't use react-lifecycles-compat with hoc that are still using the deprecated lifecycles. I am using react-lifecycles-compat in my project, the component is working fine if I import it directly, but when I try to render the hoc (tested with jss) I get this warning:

Jss(Modal) uses getDerivedStateFromProps() but also contains the following legacy lifecycles:
  componentWillMount
  componentWillReceiveProps
  componentWillUpdate
import injectSheet from 'react-jss';

// My class that use polyfill

export default injectSheet(styles)(MyClass);

Thanks!

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.