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

Overview

React · GitHub license npm version CircleCI Status PRs Welcome

React is a JavaScript library for building user interfaces.

  • Declarative: React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable, simpler to understand, and easier to debug.
  • Component-Based: Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.
  • Learn Once, Write Anywhere: We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using React Native.

Learn how to use React in your own project.

Installation

React has been designed for gradual adoption from the start, and you can use as little or as much React as you need:

You can use React as a <script> tag from a CDN, or as a react package on npm.

Documentation

You can find the React documentation on the website.

Check out the Getting Started page for a quick overview.

The documentation is divided into several sections:

You can improve it by sending pull requests to this repository.

Examples

We have several examples on the website. Here is the first one to get you started:

function HelloMessage({ name }) {
  return <div>Hello {name}</div>;
}

ReactDOM.render(
  <HelloMessage name="Taylor" />,
  document.getElementById('container')
);

This example will render "Hello Taylor" into a container on the page.

You'll notice that we used an HTML-like syntax; we call it JSX. JSX is not required to use React, but it makes code more readable, and writing it feels like writing HTML. If you're using React as a <script> tag, read this section on integrating JSX; otherwise, the recommended JavaScript toolchains handle it automatically.

Contributing

The main purpose of this repository is to continue evolving React core, making it faster and easier to use. Development of React happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving React.

Code of Conduct

Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.

Contributing Guide

Read our contributing guide to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to React.

Good First Issues

To help you get your feet wet and get you familiar with our contribution process, we have a list of good first issues that contain bugs which have a relatively limited scope. This is a great place to get started.

License

React is MIT licensed.

Comments
  • Facebook Engineers - Thank You For 2017

    Facebook Engineers - Thank You For 2017

    To all the Facebook Engineers working on open source,

    Like last year, we at Reactiflux just wanted to take a moment to thank you for all your hard work in 2017. It’s been another big year! After much anticipation React 16 was released in September, React Native has moved from v0.41 to v0.51 fixing countless bugs and adding new features, Jest has over 20 releases this year, Yarn 1.0 and Relay Modern were released, new engineers have joined (hey @calebmer, @TheSavior, @axemclion) and some have moved on (we’ll miss you @mkonicek), and that is just a tiny snapshot of 2017.

    Talking with some of you, I know that the dealing with the licensing issues this year was incredibly difficult and frustrating yet you all handled the situation in such a mature and humble manner all while continuing to iterate and innovate. Thank you! We are so happy that you can continue focusing on the work at hand, especially now that this chapter is finally closed.

    Guillermo Rauch recently tweeted, “As 2017 wraps up I believe more than ever that React is such a good idea that we will spend the rest of the decade continuing to explore its implications and applications.” We echo this sentiment and as 2017 wraps up, we also believe more than ever that you all embody the spirit of open source with such humility, servant leadership, and true focus on community driven progress that it continues to astound us. We thank you that these qualities are at the heart of our community. We thank you for all the time you have taken to join AMA’s and answer our questions on Twitter. For all the time you have taken to respond to issues and merge PR’s. Thank you for going above and beyond, again this year… as always.

    We’d like to invite the React community to reply to this thread with your own “thank you” comments to the team at Facebook. Let’s show them how grateful we are! Feel free to include experiences with the team or just how the React ecosystem has helped you as a developer.

    Sincerely,

    On behalf of the Reactiflux community: @gabegreenberg @markerikson @KyleAMathews @taion @jquense @vcarl @benigeri @Phoenixmatrix @BTMPL @kyleshevlin @slightlytyler @totaldis

    ❤️ 
    opened by gabegreenberg 264
  • React 16 RC

    React 16 RC

    The third React 16 RC is now available for public testing. 🎉

    Installation Instructions

    The RC has been published to NPM with the tag "next". Regular NPM installs will continue to use the 15.6 release. To install the RC use:

    yarn add react@next react-dom@next
    

    Or:

    npm install --save react@next react-dom@next
    

    What Does React 16 Mean for You?

    React 16 is the first release that ships with a rewrite of the React core (previously codenamed “Fiber”). This rewrite had a few goals:

    • Remove old internal abstractions that didn’t age well and hindered internal changes.
    • Let us ship some of the most requested features like returning arrays from render, recovering from component errors, and readable component stack traces for every error.
    • Enable us to start experimenting with asynchronous rendering of components for better perceived performance.

    This initial React 16.0 release is mostly focused on compatibility with existing apps. It does not enable asynchronous rendering yet. We will introduce an opt-in to the async mode later during React 16.x. We don’t expect React 16.0 to make your apps significantly faster or slower, but we’d love to know if you see improvements or regressions.

    JavaScript Environment Requirements

    React 16 depends on the collection types Map and Set. If you support older browsers and devices which may not yet provide these natively (eg <IE11), consider including a global polyfill in your bundled application, such as core-js or babel-polyfill.

    A polyfilled environment for React 16 using core-js to support older browsers might look like:

    import 'core-js/es6/map';
    import 'core-js/es6/set';
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    ReactDOM.render(
      <h1>Hello, world!</h1>,
      document.getElementById('root')
    );
    

    React also depends on requestAnimationFrame (even in test environments). A simple shim for testing environments would be:

    global.requestAnimationFrame = function(callback) {
      setTimeout(callback, 0);
    };
    

    Points of Interest

    • This is a complete rewrite of React but we expect it to work with your existing code. If you fixed all deprecation warnings introduced in 15.x, the 16 beta should work for you.
    • Third party libraries that relied on deprecated or unsupported APIs may need updates to work correctly with this new release. Now is a good time to file issues against libraries that have problems. (And tell us if we broke something!)
    • We are particularly interested in hearing about performance differences you notice between 15.x and 16.x. We don't expect any massive changes but would love to know about improvements or regressions. Please report them here!
    • The server renderer has been completely rewritten, and now offers a streaming mode (ReactDOMServer.renderToNodeStream() and ReactDOMServer.renderToStaticNodeStream()). Server rendering does not use markup validation anymore, and instead tries its best to attach to existing DOM, warning about inconsistencies. And there is no data-reactid anymore! This server renderer code is still very new, so it is likely to have issues. Please report them.
    • Hydrating a server rendered container now has an explicit API. Use ReactDOM.hydrate instead of ReactDOM.render if you're reviving server rendered HTML. Keep using ReactDOM.render if you're just doing client-side rendering.
    • React Native follows a different release cycle and will update to the beta in a future release. (It's already using an alpha release but not yet using Fiber.)

    Breaking Changes

    Error Handling

    • Previously, runtime errors used to put React into a broken state and produce cryptic errors. React 16 fixes this by introducing a special kind of components called “error boundaries”. Error boundaries can catch runtime errors in a component tree, log them, and display a fallback UI instead.
    • If there is an uncaught error in a component, and there is no error boundary up in the tree, the whole component tree will be unmounted. This helps avoid very nasty bugs where the UI has been corrupted due to an error, but it means that you need to add a few error boundaries to your app to handle the errors gracefully.
    • React 15 had a very limited undocumented support for error boundaries with a different method name. It used to be called unstable_handleError, but has been renamed to componentDidCatch.

    You can learn more about the new error handling behavior here.

    Scheduling and Lifecycle

    • ReactDOM.render() and ReactDOM.unstable_renderIntoContainer() now return null if called from inside a lifecycle method.
    • setState:
      • Calling setState with null no longer triggers an update. This allows you to decide in an updater function if you want to re-render.
      • Calling setState directly in render always causes an update. This was not previously the case. Regardless, you should not be calling setState from render.
      • setState callback (second argument) now fires immediately after componentDidMount / componentDidUpdate instead of after all components have rendered.
    • When replacing <A /> with <B />, B.componentWillMount now always happens before A.componentWillUnmount. Previously, A.componentWillUnmount could fire first in some cases.
    • Previously, changing the ref to a component would always detach the ref before that component's render is called. Now, we change the ref later, when applying the changes to the DOM.
    • It is not safe to re-render into a container that was modified by something other than React. This worked previously in some cases but was never supported. We now emit a warning in this case. Instead you should clean up your component trees using ReactDOM.unmountComponentAtNode. See this example.
    • componentDidUpdate lifecycle no longer receives prevContext param. (See #8631)
    • Shallow renderer no longer calls componentDidUpdate() because DOM refs are not available. This also makes it consistent with componentDidMount() (which does not get called in previous versions either).
    • Shallow renderer does not implement unstable_batchedUpdates() anymore.

    Packaging

    • There is no react/lib/* and react-dom/lib/* anymore. Even in CommonJS environments, React and ReactDOM are precompiled to single files (“flat bundles”). If you previously relied on undocumented React internals, and they don’t work anymore, let us know about your specific case in this issue, and we’ll try to figure out a migration strategy for you.
    • There is no react-with-addons.js build anymore. All compatible addons are published separately on npm, and have single-file browser versions if you need them.
    • The deprecations introduced in 15.x have been removed from the core package. React.createClass is now available as create-react-class, React.PropTypes as prop-types, React.DOM as react-dom-factories, react-addons-test-utils as react-dom/test-utils, and shallow renderer as react-test-renderer/shallow. See 15.5.0 and 15.6.0 blog posts for instructions on migrating code and automated codemods.
    • The names and paths to the single-file browser builds have changed to emphasize the difference between development and production builds. For example:
      • react/dist/react.jsreact/umd/react.development.js
      • react/dist/react.min.jsreact/umd/react.production.min.js
      • react-dom/dist/react-dom.jsreact-dom/umd/react-dom.development.js
      • react-dom/dist/react-dom.min.js → react-dom/umd/react-dom.production.min.js

    Known Issues

    • The server renderer crashes in production with inline styles. (https://github.com/facebook/react/issues/10299, fixed by https://github.com/facebook/react/pull/10300)
      • Fixed in 16.0.0-beta.2
    • The server renderer doesn't yet support returning arrays and strings from components.
      • Fixed in 16.0.0-beta.3
    • The server renderer still renders data-reactid somewhat unnecessarily. (https://github.com/facebook/react/issues/10306)
      • Fixed in 16.0.0-beta.3
    • Shallow renderer doesn’t pass context to componentWillReceiveProps (to be fixed by https://github.com/facebook/react/pull/10342)
      • Fixed in 16.0.0-beta.3
    • There is an issue with 'use strict' in older browsers (https://github.com/facebook/react/issues/10294#issuecomment-319490960)
      • Fixed in 16.0.0-beta.3
    • In some cases Error: null is reported instead of the real error. (https://github.com/facebook/react/issues/10321)
      • Fixed in 16.0.0-beta.3
    • There is a report that Google crawler can’t render the page using 16 (link).
      • Fixed in 16.0.0-beta.3
    • Some popular third party libraries won’t work yet (e.g. Enzyme).
    • (Please report more issues in this thread.)

    Updates

    • Released 16.0.0-beta.1 on July 24, 2017

    • Released 16.0.0-beta.2 on July 27, 2017

      • Fix a crash in server rendering.
    • Released 16.0.0-beta.3 on August 3, 2017

      • Fix strict-mode function scope problem (#10361)
      • Better error log messaging and cross-origin handling (#10353, #10373)
      • Shallow renderer improvements (#10372, #10342)
      • Edge-case context bugfix (#10334)
      • Single point of entry for server rendering (#10362)
      • etc.
    • Released 16.0.0-beta.4 on August 8, 2017

      • Warn about unresolved function as a child. #10376
      • Remove data-reactid and data-react-checksum from whitelist. #10402
      • New test renderer API features (disabled via feature flag, for now). #10377
      • And some other minor updates to slightly reduce bundle size.
    • Release 16.0.0-beta.5 on 2017-08-08

      • Fix bugs related to unmounting error boundaries #10403
      • Enable new fiber ReactTestRenderer API methods; (previously disabled behind a feature flag) #10410
    • Released 16.0.0-rc.1 on September 6, 2017

      • Fix error: undefined is not a function (evaluating 'owner.getName()') (@fxfactorial in https://github.com/facebook/react/pull/10448 and @bvaughn in https://github.com/facebook/react/pull/10520)
      • Improve error message when ReactDOM loads without React (@aweary in https://github.com/facebook/react/pull/10449)
      • Warn when nesting 15 subtree inside 16 (@sophiebits in https://github.com/facebook/react/pull/10434)
      • Don't warn about casing in SSR for non-HTML NS (@sophiebits in https://github.com/facebook/react/pull/10452)
      • Throw error to warn of mistaken loading of prod + dev React bundles (@flarnie in https://github.com/facebook/react/pull/10446)
      • Reset instance vars before calling commit phase lifecycles (@acdlite in https://github.com/facebook/react/pull/10481)
      • Warn if event listener is not a function (@aweary in https://github.com/facebook/react/pull/10453)
      • Fix bug where 1k+ react roots would cause error (@acdlite in https://github.com/facebook/react/pull/10574)
      • Allow passing some "unknown" attributes through to DOM components (@nhunzaker in https://github.com/facebook/react/pull/10385 , https://github.com/facebook/react/pull/10564 , https://github.com/facebook/react/pull/10495 and others)
      • Fix bug where <select> elements defaulted to first option, even when it was 'disabled'. (@aweary in https://github.com/facebook/react/pull/10456 and @nhunzaker in https://github.com/facebook/react/pull/10142)
    • Released 16.0.0-rc.2 on September 6, 2017

      • Fix bug where React npm packages would throw an exception on startup in browsers not supporting const natively (@sophiebits in https://github.com/facebook/react/pull/10631)
    • Released 16.0.0-rc.3 on September 14, 2017

      • Report bad dead code elimination to React DevTools (@gaearon in https://github.com/facebook/react/pull/10702)
      • Fix false positive warning when hydrating SVG after SSR (@gaearon in https://github.com/facebook/react/pull/10676)
      • Add a warning about non-lowercase custom attributes (@gaearon in https://github.com/facebook/react/pull/10699)
      • Fix a memory leak (@gaearon in https://github.com/facebook/react/pull/10680)
      • Remove deprecated entry point for the shallow renderer (@gaearon in https://github.com/facebook/react/pull/10682)
      • Remove undocumented TestUtils methods (@gaearon in https://github.com/facebook/react/pull/10681)
      • Add ReactDOM.createPortal() as an “official” API without the unstable prefix (@gaearon in https://github.com/facebook/react/pull/10675)
      • Don’t repeat Object.assign polyfill twice (@gaearon in https://github.com/facebook/react/pull/10671)
    opened by bvaughn 254
  • React Fire: Modernizing React DOM

    React Fire: Modernizing React DOM


    For latest status, see an update from June 5th, 2019: https://github.com/facebook/react/issues/13525#issuecomment-499196939


    This year, the React team has mostly been focused on fundamental improvements to React.

    As this work is getting closer to completion, we're starting to think of what the next major releases of React DOM should look like. There are quite a few known problems, and some of them are hard or impossible to fix without bigger internal changes.

    We want to undo past mistakes that caused countless follow-up fixes and created much technical debt. We also want to remove some of the abstraction in the event system which has been virtually untouched since the first days of React, and is a source of much complexity and bundle size.

    We're calling this effort "React Fire".

    🔥 React Fire

    React Fire is an effort to modernize React DOM. Our goal is to make React better aligned with how the DOM works, revisit some controversial past decisions that led to problems, and make React smaller and faster.

    We want to ship this set of changes in a future React major release because some of them will unfortunately be breaking. Nevertheless, we think they're worth it. And we have more than 50 thousands components at Facebook to keep us honest about our migration strategy. We can't afford to rewrite product code except a few targeted fixes or automated codemods.

    Strategy

    There are a few different things that make up our current plan. We might add or remove something but here's the thinking so far:

    • Stop reflecting input values in the value attribute (https://github.com/facebook/react/issues/11896). This was originally added in React 15.2.0 via https://github.com/facebook/react/pull/6406. It was very commonly requested because people's conceptual model of the DOM is that the value they see in the DOM inspector should match the value JSX attribute. But that's not how the DOM works. When you type into a field, the browser doesn't update the value attribute. React shouldn't do it either. It turned out that this change, while probably helpful for some code relying on CSS selectors, caused a cascade of bugs — some of them still unfixed to this day. Some of the fallout from this change includes: https://github.com/facebook/react/issues/7179, https://github.com/facebook/react/issues/8395, https://github.com/facebook/react/issues/7328, https://github.com/facebook/react/issues/7233, https://github.com/facebook/react/issues/11881, https://github.com/facebook/react/issues/7253, https://github.com/facebook/react/pull/9584, https://github.com/facebook/react/pull/9806, https://github.com/facebook/react/pull/9714, https://github.com/facebook/react/pull/11534, https://github.com/facebook/react/pull/11746, https://github.com/facebook/react/pull/12925. At this point it's clearly not worth it to keep fighting the browser, and we should revert it. The positive part of this journey is that thanks to tireless work from our DOM contributors (@nhunzaker, @aweary, @jquense, and @philipp-spiess) we now have detailed DOM test fixtures that will help us avoid regressions.

    • Attach events at the React root rather than the document (https://github.com/facebook/react/issues/2043). Attaching event handlers to the document becomes an issue when embedding React apps into larger systems. The Atom editor was one of the first cases that bumped into this. Any big website also eventually develops very complex edge cases related to stopPropagation interacting with non-React code or across React roots (https://github.com/facebook/react/issues/8693, https://github.com/facebook/react/pull/8117, https://github.com/facebook/react/issues/12518). We will also want to attach events eagerly to every root so that we can do less runtime checks during updates.

    • Migrate from onChange to onInput and don’t polyfill it for uncontrolled components (https://github.com/facebook/react/issues/9657). See the linked issue for a detailed plan. It has been confusing that React uses a different event name for what's known as input event in the DOM. While we generally avoid making big changes like this without significant benefit, in this case we also want to change the behavior to remove some complexity that's only necessary for edge cases like mutating controlled inputs. So it makes sense to do these two changes together, and use that as an opportunity to make onInput and onChange work exactly how the DOM events do for uncontrolled components.

    • Drastically simplify the event system (https://github.com/facebook/react/issues/4751). The current event system has barely changed since its initial implementation in 2013. It is reused across React DOM and React Native, so it is unnecessarily abstract. Many of the polyfills it provides are unnecessary for modern browsers, and some of them create more issues than they solve. It also accounts for a significant portion of the React DOM bundle size. We don't have a very specific plan here, but we will probably fork the event system completely, and then see how minimal we can make it if we stick closer to what the DOM gives us. It's plausible that we'll get rid of synthetic events altogether. We should stop bubbling events like media events which don’t bubble in the DOM and don’t have a good reason to bubble. We want to retain some React-specific capabilities like bubbling through portals, but we will attempt to do this via simpler means (e.g. re-dispatching the event). Passive events will likely be a part of this.

    • classNameclass (https://github.com/facebook/react/issues/4331, see also https://github.com/facebook/react/issues/13525#issuecomment-417818906 below). This has been proposed countless times. We're already allowing passing class down to the DOM node in React 16. The confusion this is creating is not worth the syntax limitations it's trying to protect against. We wouldn't do this change by itself, but combined with everything else above it makes sense. Note we can’t just allow both without warnings because this makes it very difficult for a component ecosystem to handle. Each component would need to learn to handle both correctly, and there is a risk of them conflicting. Since many components process className (for example by appending to it), it’s too error-prone.

    Tradeoffs

    • We can't make some of these changes if we aim to keep exposing the current private React event system APIs for projects like React Native Web. However, React Native Web will need a different strategy regardless because React Fabric will likely move more of the responder system to the native side.

    • We may need to drop compatibility with some older browsers, and/or require more standalone polyfills for them. We still care about supporting IE11 but it's possible that we will not attempt to smooth over some of the existing browser differences — which is the stance taken by many modern UI libraries.

    Rollout Plan

    At this stage, the project is very exploratory. We don't know for sure if all of the above things will pan out. Because the changes are significant, we will need to dogfood them at Facebook, and try them out in a gradual fashion. This means we'll introduce a feature flag, fork some of the code, and keep it enabled at Facebook for a small group of people. The open source 16.x releases will keep the old behavior, but on master you will be able to run it with the feature flag on.

    I plan to work on the project myself for the most part, but I would very much appreciate more discussion and contributions from @nhunzaker, @aweary, @jquense, and @philipp-spiess who have been stellar collaborators and have largely steered React DOM while we were working on Fiber. If there's some area you're particularly interested in, please let me know and we'll work it out.

    There are likely things that I missed in this plan. I'm very open to feedback, and I hope this writeup is helpful.

    Component: DOM Type: Big Picture React Core Team 
    opened by gaearon 228
  • Add fragment API to allow returning multiple components from render

    Add fragment API to allow returning multiple components from render


    Note from maintainers:

    We know this is an issue and we know exactly what set of problem can be solved. We want this too but it is a hard problem with our current architecture. Additional comments expressing desire for this feature are not helpful. Feel free to subscribe to the issue (there's button in the right hand column) but do not comment unless you are adding value to the discussion. "Me too" and "+1" are not valuable, nor are use cases that have already been written in the comments (e.g., we know that you can't put <tr> or <dd> elements with a <div>).


    Consider the following:

    var ManagePost = React.createClass({
    
      render: function() {
        var posts = this.props.posts
    
        var something;
        var somethingelse;
    
        var row = posts.map(function(post){
          return(
            <div>
              <div className="col-md-8">
              </div>
              <div className="cold-md-4">
              </div>
            </div>
          )
        });
    
        return (
            {row}
        );
      }
    
    });
    

    If you remove the <div></div> in the map, you get the following error: Adjacent XJS elements must be wrapped in an enclosing tag

    it isn't till I re-add the surrounding, and rather pointless, divs that it compiles with out issue. I am running 0.11.1

    Is this being addressed? It adds extra, and again - IMO - useless and pointless html to the page, that while harming nothing - looks messy and unprofessional. Maybe I am just doing something wrong, please enlighten me if I am.

    opened by AdamKyle 148
  • Explore encouraging users to not ship DEV mode to production

    Explore encouraging users to not ship DEV mode to production

    Do you want to request a feature or report a bug? Feature

    What is the current behavior? Developers meaning to do the right thing will often accidentally ship DEV mode to production rather than PROD mode. This can have a significant impact on performance. Although DEV->PROD is a one line change, it's something React could explore encouraging.

    There's great nuance here and I know that there's balance to be struck between the overall DX value this brings vs UX. Another challenge is that the change itself is trivial to make. It's unclear whether the right solution here is better defaults or stronger advocacy. Folks like @sebmarkbage have been acknowledging that this is a known issue so perhaps there's room for discussion to help improve this.

    He's also noted that a switch from no warnings to DEV may require some folks to fix whole codebases which is also suboptimal. There may be an in-between solution worth talking about here however.

    What is the expected behavior?

    React encourages users to ship PROD mode to production rather than DEV. I would be open to a solution that is either provided at the library layer (or somehow tackled during build/bundling time by Webpack) that tries to ameliorate this.

    This thread had a number of suggestions ranging from localhost detection, to alerts to injecting 'dev mode' messages to the DOM if used in a production environment. Something like this:

    Alternatively, @thelarkinn was proposing that we tried to standardize on ENV configs being required to better facilitate detection of messaging like this. It's unclear which of these would be the most realistic. There are likely other ideas React core might have around how to tackle the problem.

    Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

    All recent versions.

    This thread from @jordwalke prompted this issue. I think he also makes a fair point regarding benchmarks, but I care about how we can help folks ship the prod experience y'all have worked on optimizing to end customers in all it's glory.

    opened by addyosmani 143
  • Provide more ways to bail out inside Hooks

    Provide more ways to bail out inside Hooks

    There's a few separate issues but I wanted to file an issue to track them in general:

    • useState doesn't offer a way to bail out of rendering once an update is being processed. This gets a bit weird because we actually process updates during the rendering phase. So we're already rendering. But we could offer a way to bail on children. Edit: we now do bail out on rendering children if the next state is identical.
    • useContext doesn't let you subscribe to a part of the context value (or some memoized selector) without fully re-rendering. Edit: see https://github.com/facebook/react/issues/15156#issuecomment-474590693 for solutions to this.
    Component: Hooks 
    opened by gaearon 140
  • Implement Sideways Data Loading

    Implement Sideways Data Loading

    This is a first-class API for sideways data loading of stateless (although potentially memoized) data from a global store/network/resource, potentially using props/state as input.

    type RecordOfObservables = { [key:string]: Observable<mixed> };
    
    class Foo {
    
      observe(): RecordOfObservables {
        return {
          myContent: xhr(this.props.url)
        };
      }
    
      render() {
        var myContent : ?string = this.data.myContent;
        return <div>{myContent}</div>;
      }
    
    }
    

    observe() executes after componentWillMount/componentWillUpdate but before render.

    For each key/value in the record. Subscribe to the Observable in the value.

    subscription = observable.subscribe({ onNext: handleNext });
    

    We allow onNext to be synchronously invoked from subscribe. If it is, we set:

    this.data[key] = nextValue;
    

    Otherwise we leave it as undefined for the initial render. (Maybe we set it to null?)

    Then render proceeds as usual.

    Every time onNext gets invoked, we schedule a new "this.data[key]" which effectively triggers a forcedUpdate on this component. If this is the only change, then observe is not reexecuted (componentWillUpdate -> render -> componentDidUpdate).

    If props / state changed (i.e. an update from recieveProps or setState), then observe() is reexecuted (during reconciliation).

    At this point we loop over the new record, and subscribe to all the new Observables.

    After that, unsubscribe to the previous Observables.

    subscription.dispose();
    

    This ordering is important since it allows the provider of data to do reference counting of their cache. I.e. I can cache data for as long as nobody listens to it. If I unsubscribed immediately, then the reference count would go down to zero before I subscribe to the same data again.

    When a component is unmounted, we automatically unsubscribe from all the active subscriptions.

    If the new subscription didn't immediately call onNext, then we will keep using the previous value.

    So if my this.props.url from my example changes, and I'm subscribing to a new URL, myContent will keep showing the content of the previous url until the next url has fully loaded.

    This has the same semantics as the <img /> tag. We've seen that, while this can be confusing and lead to inconsistencies it is a fairly sane default, and it is easier to make it show a spinner than it would be to have the opposite default.

    Best practice might be to immediately send a "null" value if you don't have the data cached. Another alternative is for an Observable to provide both the URL (or ID) and the content in the result.

    class Foo {
    
      observe() {
        return {
          user: loadUser(this.props.userID)
        };
      }
    
      render() {
        if (this.data.user.id !== this.props.userID) {
          // Ensure that we never show inconsistent userID / user.name combinations.
          return <Spinner />;
        }
        return <div>Hello, {this.data.user.name} [{this.props.userID}]!</div>;
      }
    
    }
    

    We should use the RxJS contract of Observable since that is more in common use and allows synchronous execution, but once @jhusain's proposal is in more common use, we'll switch to that contract instead.

    var subscription = observable.subscribe({ onNext, onError, onCompleted });
    subscription.dispose();
    

    We can add more life-cycle hooks that respond to these events if necessary.

    Note: This concept allows sideways data to behave like "behaviors" - just like props. This means that we don't have to overload the notion state for these things. It allows for optimizations such as throwing away the data only to resubscribe later. It is restorable.

    Type: Big Picture Component: Component API 
    opened by sebmarkbage 136
  • Express more tests via public API

    Express more tests via public API

    This is a great contribution opportunity. We need to rewrite more unit tests in terms of public API.

    This means that they can only import npm entry points like react, react-dom, react-dom/test-utils, react-test-renderer, etc, but not internal modules like SyntheticEvent or ReactDOMComponentTree. The “bad” requires are already marked with a TODO in tests so you won’t miss them.

    To help with this:

    1. Find // TODO: can we express this test with only public API? in the unclaimed test files below.
    2. Comment in this issue if you want to take a particular unit test file, with its name.
    3. Submit a PR that rewrites the test to use public APIs instead.

    Step 3 requires some thinking. You can use previous examples where we rewrote tests with public API for inspiration. For example:

    • https://github.com/facebook/react/pull/10429
    • https://github.com/facebook/react/pull/10281
    • https://github.com/facebook/react/pull/9080
    • https://github.com/facebook/react/pull/8148

    Generally, you need to think about how the behavior you’re testing actually reproduces in a React app, and then test for that. In rare cases it may involve exposing some API as public which we’ll need to discuss separately, so don’t hesitate to start a discussion! If you can’t figure out how to rewrite some particular test with a public API, comment here and we can brainstorm.

    Here is the full list of tests that need to change. Some of them may be simple one-liner changes, some may involve a bit of a rewrite, some may require rewriting from scratch. Some may even be impossible, but research leading to that conclusion is still very valuable and we’d love to know that.

    Try them and let us know:

    Update: all tests are taken now. Subscribe to this issue! They might free up in the future if somebody doesn’t have the time to finish the work. We’ll comment if some test becomes available to try again.

    • [ ] ReactBrowserEventEmitter-test.js (taken by @madeinfree, see https://github.com/facebook/react/issues/11299#issuecomment-355188567)
    • [ ] getNodeForCharacterOffset-test.js (taken by @accordeiro)
    • [ ] ReactErrorUtils-test.js (taken by @reznord)
    • [x] BeforeInputEventPlugin-test.js + FallbackCompositionState-test.js (taken by @GordyD)
    • [x] validateDOMNesting-test.js (taken by @anushreesubramani) https://github.com/facebook/react/pull/11742
    • [x] ReactIncrementalPerf-test.js (taken by @dphurley) https://github.com/facebook/react/pull/11724
    • [x] SelectEventPlugin-test.js (taken by @skiritsis) https://github.com/facebook/react/issues/11299
    • [x] ReactTreeTraversal-test.js (taken by @timjacobi) https://github.com/facebook/react/pull/11664
    • [x] SyntheticKeyboardEvent-test.js + getEventCharCode-test.js (taken by @aarboleda1)
    • [x] escapeTextContentForBrowser-test.js (taken by @jeremenichelli) https://github.com/facebook/react/pull/11331
    • [x] inputValueTracking-test.js
    • [x] quoteAttributeValueForBrowser-test.js (taken by @jeremenichelli) https://github.com/facebook/react/pull/11331
    • [x] ReactDOMComponent-test.js (taken by @AudyOdi) https://github.com/facebook/react/pull/11337
    • [x] ReactDOMComponentTree-test.js (taken by @GordyD) https://github.com/facebook/react/pull/11383
    • [x] ReactDOMEventListener-test.js (taken by @enapupe) https://github.com/facebook/react/pull/11327
    • [x] ReactDOMInput-test.js (taken by @SadPandaBear) https://github.com/facebook/react/pull/11309
    • [x] ReactDOMServerIntegration-test.js (taken by @minerado)
    • [x] setInnerHTML-test.js (taken by @silvestrijonathan) https://github.com/facebook/react/pull/11385 https://github.com/facebook/react/pull/11631
    • [x] getEventKey-test.js (taken by @mjw56) https://github.com/facebook/react/pull/11317
    • [x] SyntheticClipboardEvent-test.js (taken by @smaniotto) https://github.com/facebook/react/pull/11365
    • [x] SyntheticEvent-test.js (taken by @timjacobi) https://github.com/facebook/react/pull/11525
    • [x] SyntheticWheelEvent-test.js (taken by @douglasgimli) https://github.com/facebook/react/pull/11367
    • [x] ChangeEventPlugin-test.js (taken by @Ethan-Arrowood) https://github.com/facebook/react/pull/11333
    • [x] EnterLeaveEventPlugin-test.js (taken by @accordeiro) https://github.com/facebook/react/pull/11316
    • [x] ReactCoroutine-test.js (taken by @jstejada)
    • [x] ReactFiberHostContext-test.js (taken by @adsonpleal)

    First-time contributor? Refer to our contribution instructions.

    Not clear how to fix a specific test? Comment with what you tried, and we can brainstorm.

    If you gave up on some test, please post your findings in a comment so we can decide what to do next. It’s fine if you just didn’t find the time or couldn’t figure it out—we can try to help, and maybe somebody else can pick it up later.


    Difficulty: medium good first issue (taken) 
    opened by gaearon 133
  • Allow custom (nonstandard) attributes.

    Allow custom (nonstandard) attributes.

    Various frameworks uses custom attributes. React could allow to extend default data- and aria- prefixes. Something like this:

    React.registerCustomAttributePrefix('e-');
    React.registerCustomAttributePrefix('ng-');
    
    Component: DOM 
    opened by steida 131
  • Unhelpful warning for `act` for react-dom@16.8

    Unhelpful warning for `act` for [email protected]

    Do you want to request a feature or report a bug?

    Feature/Improvement

    What is the current behavior?

    If there is test code that should be wrapped in act(...) then the current warning is given:

     console.error node_modules/react-dom/cjs/react-dom.development.js:506
        Warning: An update to null inside a test was not wrapped in act(...).
    
        When testing, code that causes React state updates should be wrapped into act(...):
    
        act(() => {
          /* fire events that update state */
        });
        /* assert on the output */
    
        This ensures that you're testing the behavior the user would see in the browser. Learn more at https://fb.me/react-wrap-tests-with-act
    

    When upgrading a large code base, this is basically useless.

    What is the expected behavior?

    Provide at least the test name if not the line number of code that triggered the warning.

    Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

    [email protected] [email protected]

    Type: Feature Request 
    opened by ncphillips 128
  • Consider re-licensing to AL v2.0, as RocksDB has just done

    Consider re-licensing to AL v2.0, as RocksDB has just done

    Hi there,

    The Apache Software Foundation Legal Affairs Committee has announced that the so-called 'Facebook BSD+Patents License' is no longer allowed to be used as a direct dependency in Apache projects.

    This has lead to a lot of upset and frustration in the Apache community, especially from projects requiring similarly-licensed code as direct dependencies - the chief of these being RocksDB.

    However, we (the Apache Software Foundation) have just received word that RocksDB will be re-licensing their code under the dual Apache License v2.0 and GPL 2 licenses.

    As a user of React.JS in an ASF top-level project (Apache CouchDB), please consider re-licensing React.JS under similar terms. Otherwise, many ASF projects such as our own will have to stop relying on and building with React.

    A previous bug (#9760) suggested I mention @lacker in this issue when asking licensing questions, so I'm doing so.

    Thank you kindly for your consideration.

    opened by wohali 128
  • Bug: JSX string interpolation throws erroneous error on `hydrateRoot`

    Bug: JSX string interpolation throws erroneous error on `hydrateRoot`

    hydrateRoot seems to have issues with jsx string interpolation. hydrateRoot seems to see the the inline string as separate on the client and can't match the unbroken string rendered by the server.

    react-dom.development.js:73 Warning: Text content did not match. Server: "Jaguar shark!" Client: "Jaguar " at p at App1
    react-dom.development.js:73 Warning: An error occurred during hydration. The server HTML was replaced with client content in <div>.
    

    React version: 18.2.0

    Steps To Reproduce

    This is the simplest example I could muster, obviously I would not normally write JSX in this fashion but it illustrates the issue.

    HTML:

    <div id="root"><p>Jaguar shark!</p></div>
    

    JS:

    const App = () => (<p>Jaguar {'shark!'}</p>);
    
    ReactDOM.hydrateRoot(document.getElementById("root"), <App />, {
      onRecoverableError: (err) => {
        alert('error found: ' + err);
      }
    });
    

    Link to code example: https://codepen.io/Dickie81/pen/xxJVwmp

    The current behavior

    Throws error. Re-renders dom.

    The expected behavior

    hydrates without complaint

    Status: Unconfirmed 
    opened by dickie81 0
  • Bug: 'exhaustive-deps' lint rule warns that

    Bug: 'exhaustive-deps' lint rule warns that "Outer scope values" aren't valid when a hook is inside a function

    React version: 18.1.0

    Steps To Reproduce

    Inside a functional component, an inner function with a dependency on value from an outer function triggers the warning, "Outer scope values like '....' aren't valid dependencies because mutating them doesn't re-render the component."

    Here's the crux of the problem

    const List = (props: IListProps) => {
      const { items } = props;
    
      // Using the useMemo hook here doesn't complain, e.g. -
      // const names = useMemo(() => items.map(item => item.name), [items]);
    
      // Using the useMemo hook inside a function complains
      const names = useItemNames();
    
      return (
        <>
          <h2>There are {items.length} items in the list</h2>
          <section>
            {names.map(name => (
              <div>{name}</div>
            ))}
          </section>
        </>
      );
    
      ////////////////////
    
      function useItemNames() {
        // es-lint warns here: Outer scope values like 'items' aren't valid dependencies 
        // because mutating them doesn't re-render the component
        return useMemo(() => items.map(item => item.name), [items]);
      }
    };
    

    Link to code example: https://codesandbox.io/s/custom-hook-repro-3wfly

    The current behavior

    The eslint rule will complain about unneccessary dependencies.

    The expected behavior

    The eslint rule shouldn't be triggered.

    This is a reopen and copy of https://github.com/facebook/react/issues/17060 by @gerrod

    Status: Unconfirmed 
    opened by finnp 0
  • custom hook does not work in the new version of react dom

    custom hook does not work in the new version of react dom

    In my projects, I very often use a custom hook to emulate the behavior of componentDidUpdate

    const [lesson, setLesson] = useState(''); const ref = useRef(); useEffect(() => { if (!ref.current) { ref.current = true; } else { do something } }, [lesson]);

    With this combination, the custom hook stopped working

    "react": "^18.2.0", "react-dom": "^18.2.0",

    import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App';

    const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> </React.StrictMode>, );

    What is the problem?

    Status: Unconfirmed 
    opened by Sinevik 0
  • Bump json5 from 2.1.3 to 2.2.2

    Bump json5 from 2.1.3 to 2.2.2

    Bumps json5 from 2.1.3 to 2.2.2.

    Release notes

    Sourced from json5's releases.

    v2.2.2

    • Fix: Properties with the name __proto__ are added to objects and arrays. (#199) This also fixes a prototype pollution vulnerability reported by Jonathan Gregson! (#295).

    v2.2.1

    • Fix: Removed dependence on minimist to patch CVE-2021-44906. (#266)

    v2.2.0

    • New: Accurate and documented TypeScript declarations are now included. There is no need to install @types/json5. (#236, #244)
    Changelog

    Sourced from json5's changelog.

    v2.2.2 [code, diff]

    • Fix: Properties with the name __proto__ are added to objects and arrays. (#199) This also fixes a prototype pollution vulnerability reported by Jonathan Gregson! (#295).

    v2.2.1 [code, diff]

    • Fix: Removed dependence on minimist to patch CVE-2021-44906. (#266)

    v2.2.0 [code, diff]

    • New: Accurate and documented TypeScript declarations are now included. There is no need to install @types/json5. (#236, #244)
    Commits
    • 14f8cb1 2.2.2
    • 10cc7ca docs: update CHANGELOG for v2.2.2
    • 7774c10 fix: add proto to objects and arrays
    • edde30a Readme: slight tweak to intro
    • 97286f8 Improve example in readme
    • d720b4f Improve readme (e.g. explain JSON5 better!) (#291)
    • 910ce25 docs: fix spelling of Aseem
    • 2aab4dd test: require tap as t in cli tests
    • 6d42686 test: remove mocha syntax from tests
    • 4798b9d docs: update installation and usage for modules
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    CLA Signed dependencies 
    opened by dependabot[bot] 0
  • Problem import css custom files in tailwindcss with react app

    Problem import css custom files in tailwindcss with react app

    tailwindcss.com provide css file import syntax like down below Import our provided CSS files.

    @import "tailwindcss/base";
    @import "./custom-base-styles.css";
    
    @import "tailwindcss/components";
    @import "./custom-components.css";
    
    @import "tailwindcss/utilities";
    @import "./custom-utilities.css";
    

    I'm using the same way in my react app but it is problem.

    @import "tailwindcss/base";
    @import "tailwindcss/components";
    @import "./my-components.css";
    @import "tailwindcss/utilities";
    

    The problem here is my custom style on top of the build.css file.

    .my-btn {
      styles ... 
    }
    /*
    ! tailwindcss v3.2.4 | MIT License | https://tailwindcss.com
    */*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box} ....
    /*# sourceMappingURL=main.f601fced.css.map*/
    
    "react": "^18.2.0",
    "tailwindcss": "^3.2.4"
    

    Gitgub repository

    Status: Unconfirmed 
    opened by jabed-dev 0
  • devtools: Use context displayName for context hook name

    devtools: Use context displayName for context hook name

    Summary

    When inspecting the hooks of an element, the display name of the passed context is now used for the context hook (with a fallback to the previous "Context" name).

    Before: Screenshot from 2023-01-01 19-07-45

    After:

    Screenshot from 2023-01-01 19-40-32

    How did you test this change?

    • [x] added tests
    • [x] react-devtools-shell (see attached screenshots)
    CLA Signed React Core Team 
    opened by eps1lon 0
Releases(v18.2.0)
Owner
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
Facebook
:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Inferno is an insanely fast, React-like library for building high-performance user interfaces on both the client and server. Description The main obje

Inferno 15.6k Dec 31, 2022
A declarative, HTML-based language that makes building web apps fun

A declarative, HTML-based language that makes building web apps fun ?? Docs ∙ Try Online ∙ Contribute ∙ Get Support Intro Marko is HTML re-imagined as

Marko 12k Jan 3, 2023
Tiny (2 KB) turboboosted JavaScript library for creating user interfaces.

Develop web applications with 100% JavaScript and web standards. ?? RE:DOM is a tiny (2 KB) UI library by Juha Lindstedt and contributors, which adds

RE:DOM 3.2k Jan 3, 2023
🌙 The minimal & fast library for functional user interfaces

Moon The minimal & fast library for functional user interfaces Summary ?? Small file size (2kb minified + gzip) ⚡ Blazing fast view rendering ?? Purel

Kabir Shah 6k Jan 2, 2023
jCore - JavaScript library for building UI components

JavaScript library for building UI components

iOnStage 11 Jan 21, 2022
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

Supporting Vue.js Vue.js is an MIT-licensed open source project with its ongoing development made possible entirely by the support of these awesome ba

vuejs 201.6k Jan 7, 2023
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

vue-next This is the repository for Vue 3.0. Quickstart Via CDN: <script src="https://unpkg.com/vue@next"></script> In-browser playground on Codepen S

vuejs 34.6k Jan 4, 2023
Relay is a JavaScript framework for building data-driven React applications.

Relay · Relay is a JavaScript framework for building data-driven React applications. Declarative: Never again communicate with your data store using a

Facebook 17.5k Jan 1, 2023
A JavaScript Framework for Building Brilliant Applications

mithril.js What is Mithril? Installation Documentation Getting Help Contributing What is Mithril? A modern client-side JavaScript framework for buildi

null 13.5k Dec 28, 2022
A Web Component compiler for building fast, reusable UI components and static site generated Progressive Web Apps

Stencil: A Compiler for Web Components and PWAs npm init stencil Stencil is a simple compiler for generating Web Components and static site generated

Ionic 11.3k Jan 4, 2023
The tiny framework for building hypertext applications.

Hyperapp The tiny framework for building hypertext applications. Do more with less—We have minimized the concepts you need to learn to get stuff done.

Jorge Bucaran 18.9k Jan 1, 2023
🐰 Rax is a progressive React framework for building universal application. https://rax.js.org

Rax is a progressive React framework for building universal applications. ?? Write Once, Run Anywhere: write one codebase, run with Web, Weex, Node.js

Alibaba 7.8k Dec 31, 2022
🙌 Check if a Discord user is sponsoring you/someone on GitHub and give them roles!

Discord: Is User Sponsor? A bot that gives roles if a user is supporting you on GitHub! Uses Discord OAuth and Discord GitHub integration to get user'

EGGSY 18 Jun 27, 2022
KioskBoard - A pure JavaScript library for using virtual keyboards.

KioskBoard - Virtual Keyboard A pure JavaScript library for using virtual keyboards. Current Version 2.0.0 * Documentation and Demo https://furcan.git

Furkan MT 177 Dec 29, 2022
A JavaScript UI Library with JQuery like syntax

A JavaScript UI Library with JQuery like syntax. (Beta)

Sijey 5 Jan 16, 2022
Simple and elegant component-based UI library

Simple and elegant component-based UI library Custom components • Concise syntax • Simple API • Tiny Size Riot brings custom components to all modern

Riot.js 14.7k Jan 4, 2023
ENS Avatar resolver library for both nodejs and browser.

ens-avatar Avatar resolver library for both nodejs and browser. Getting started Prerequisites Have your web3 provider ready (web3.js, ethers.js) [Only

Ethereum Name Service (ENS) 27 Dec 30, 2022
Our original Web Component library.

Polymer ℹ️ Note: This is the current stable version of the Polymer library. At Google I/O 2018 we announced a new Web Component base class, LitElement

Polymer Project 21.9k Jan 3, 2023
🙋‍♀️ 3kb library for tiny web apps

3kb library for tiny web apps. Sometimes, all you want to do is to try and do something—No boilerplate, bundlers, or complex build processes. Lucia ai

Aiden Bai 699 Dec 27, 2022