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
  • Problem import css custom files in tailwindcss with react app

    Problem import css custom files in tailwindcss with react app

    tailwindcss.com import css files 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 that my custom style is top

    .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"
    
    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
  • Bug: Chrome devtools conflict while watching WebSocket in a React page

    Bug: Chrome devtools conflict while watching WebSocket in a React page

    Well, this might be a strange question, but there are some differences about the behavior of iframes between a native h5 page and a React page.

    • Native h5 Page

      Here is a native h5 page with an iFrame. The iframe will create a WebSocket connection. We can see the value of Time is Pending while the connection is still active.

      Image here

      Then after I removed this iframe as a child from document, the value of Time became the time the connection lasted.

      Image here

    However, in a React Page, something strange happens.

    • React Page

      Every added iframe would create a WebSocket connection in Pending status.

      Image here

      But when I remove them, the value of Time wouldn't change into the time they lasted, but still in Pending status.

      Image here

      Here is my code:

    function App() {
      const [frames, setFrames] = useState([]);
    
      const onAdd = useCallback(() => {
        const iFrame = (
          <iframe src='http://127.0.0.1:8080/iframe.html' />
        );
    
        setFrames((frames) => [
          ...frames,
          iFrame,
        ]);
      }, []);
    
      const onDel = useCallback(() => {
        setFrames((frames) => [
          ...frames.slice(0, frames.length - 1),
        ]);
      }, []);
    
      return (
        <div className="App">
          <div>
            <button onClick={onAdd}>+1</button>
            <button onClick={onDel}>-1</button>
          </div>
          <div>
            {
              frames.map((frame, index) => {
                return (
                  <React.Fragment key={index}>
                    {frame}
                  </React.Fragment>
                )
              })
            }
          </div>
        </div>
      );
    }
    

    I tried to make some logs in my WebSocket Server, and it seemed that the connections have been disconnected already.

    I'm a freshman in frontend development, so this is a strange behavior as for me. I wonder if this caused by memory leak or something else.

    Sincerely waiting for your answer.

    Status: Unconfirmed 
    opened by ch1ny 0
  • Bug: React Re-Renders Component When Set State is The Exact Same, but Only Once

    Bug: React Re-Renders Component When Set State is The Exact Same, but Only Once

    https://codesandbox.io/s/blissful-jepsen-luo8ce?file=/src/App.js

    In this code, I set a state to true when a button is clicked. On the first click the log statement inside the handler runs, the state is set to true, the component re-renders, and 'the state is true' prints. On the second click, this happens again- why? I am setting state to a duplicate value so the component shouldn't re-render. Even if it were to re-render, it only ever happens twice, the third click and onwards only run the console.log inside the handler, not inside the component itself.

    Status: Unconfirmed 
    opened by agrawalishaan 3
  • Bug: BetaDocs - application tutorial tic-tac-toe zip error

    Bug: BetaDocs - application tutorial tic-tac-toe zip error

    React version:

    Steps To Reproduce

    1. In the CodeSandbox tab you opened earlier, press the top-left corner button to open the menu, and then choose File > Export to ZIP in that menu to download an archive of the files locally
    2. See the structure of the files.

    Link to code example: tutorial-tic-tac-toe

    The current behavior

    Incorrect folder structure, throwing an error when performing an "npm start".

    The expected behavior

    Zip file must contain the same folder structure as the online editor. And it should work when running "npm install".

    link to correctly organized folders

    Status: Unconfirmed 
    opened by fernandomk6 0
  • React devtools stuck at Loading React Element Tree...

    React devtools stuck at Loading React Element Tree...

    Have tried re-installing both extension and chrome.

    OS: Ubuntu 20.10 Chrome: 107.0.5304.87 (Official Build) (64-bit) Scenario: Dev tools shows

     Loading React Element Tree...
    
    If this seems stuck, please follow the [troubleshooting instructions](https://github.com/facebook/react/tree/main/packages/react-devtools#the-issue-with-chrome-v101-and-earlier-versions).
    

    on local development servers.

    opened by ananthakrishna-hs 1
Releases(v18.2.0)
Owner
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
Facebook
A small component based app library composing user interfaces and apps.

See https://vibejs.com for ongoing documentation and info. VibeJS A small component based JavaScript library to build user interfaces and apps. If you

Bret 20 Nov 16, 2022
Boilerplate to get started building React-based interfaces for Crestron using CH5

Getting Started with Crestron UI This project was bootstrapped with Create React App. Example component communicating with the Crestron-CH5 library: i

Mukund Salia 3 Apr 25, 2022
Bdc-walkthrough - An Angular Material library for displaying walk-through pop-ups and dialogs using a declarative way.

Material walk-through library An Angular Material library for displaying walk-through pop-ups and dialogs using a declarative way. Show Demo Prerequis

Broadcom Inc 65 Dec 14, 2022
Declarative routing for React

React Router Declarative routing for React Docs View the docs here Migrating from 2.x/3.x? 3.x docs 2.x docs Packages This repository is a monorepo th

React Training 49.3k Jan 9, 2023
🌊 A flexible and fun JavaScript file upload library

A JavaScript library that can upload anything you throw at it, optimizes images for faster uploads, and offers a great, accessible, silky smooth user

pqina 13.1k Dec 31, 2022
As a user, I want to be able to post about travel locations and provide comments and ratings. As a user, I want to be able to look at other users posts and search travel locations by rating.

Travel-bug https://travelbug-project.herokuapp.com/ Table of Contents User-Story Description Installation Usage Contributions Tests License Questions

Megan 3 Mar 2, 2022
A bookstore app that allows a user add a book, displays added book with reviews and rating for each book and allows a user delete a book.

BOOKSTORE A bookstore app that allows a user add a book, displays added book with reviews and rating for each book and allows a user delete a book. Bu

Promise Okechukwu 7 Nov 1, 2022
A very lightweight and flexible accessible modal dialog script.

A11y Dialog This is a lightweight (1.3Kb) yet flexible script to create accessible dialog windows. Documentation ↗ Demo on CodeSandbox ↗ Features: Clo

Kitty Giraudel 2.1k Jan 2, 2023
🏎 A set of primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components.

downshift ?? Primitives to build simple, flexible, WAI-ARIA compliant React autocomplete, combobox or select dropdown components. Read the docs | See

Downshift 11.1k Dec 28, 2022
Gnome Shell extension to provide a flexible applications dock (WIP).

Flexi Dock (WIP) Gnome Shell extension to provide a flexible applications dock. Installation The easiest way to install this extension is via the offi

Hardpixel 3 Aug 29, 2022
Provide solutions to make your app flexible for different screen sizes, different devices.

react-native-size-scaling Provide solutions to make your app flexible for different screen sizes, different devices, based on your device's pixel rati

Hoà Phan 33 Dec 23, 2022
The best JavaScript Data Table for building Enterprise Applications. Supports React / Angular / Vue / Plain JavaScript.

Module SonarCloud Status ag-grid-community ag-grid-enterprise AG Grid AG Grid is a fully-featured and highly customizable JavaScript data grid. It del

AG Grid 9.5k Dec 30, 2022
Accessible, unstyled, open-sourced, and fully functional react component library for building design systems

DORAI UI Accessible, unstyled, open-sourced and fully functional react component library for building design systems Documentation site coming soon St

Fakorede Boluwatife 38 Dec 30, 2022
Router JS 💽 Simple Router building in JavaScript

Router JS ?? Simple Router building in JavaScript

David Montaño Tamayo 1 Feb 12, 2022
⚛️ Hooks for building fast and extendable tables and datagrids for React

Hooks for building lightweight, fast and extendable datagrids for React Enjoy this library? Try them all! React Query, React Form, React Charts Visit

Tanner Linsley 20.3k Jan 3, 2023
A frontend Framework for building B2B applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Material Design

react-admin A frontend Framework for building data-driven applications running in the browser on top of REST/GraphQL APIs, using ES6, React and Materi

marmelab 21.2k Dec 30, 2022
Finished code and notes from EFA bonus class on building a React project without create-react-app

React From Scratch Completed Code This is the completed code for the EFA bonus class on building a React project from scratch. Included are also markd

Conor Broaders 3 Oct 11, 2021
React-app - Building volume rendering web app with VTK.js,react & HTML Using datasets provided in vtk examples (head for surface rendering and chest for ray casting)

SBE306 Assignment 4 (VTK) data : Directory containing Head and Ankle datasets Description A 3D medical viewer built with vtk-js Team Team Name : team-

Mustafa Megahed  2 Jul 19, 2022
Developer Dao FM is where you can chill and listen to Lofi music while building cool stuff!

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Developer DAO 9 Jul 21, 2022