Skip to content

Need way to receive and pass down all context (regardless of contextTypes/childContextTypes) #8262

Closed

Description

@moodysalem

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

What is the current behavior?
A component can only access via this.context anything defined in childContextTypes of the parent and contextTypes of the child

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template: https://jsfiddle.net/reactjs/69z2wepo/).
N/A

What is the expected behavior?
Would like a way to take all the context available regardless of contextTypes and also pass down, via context, variables not defined in childContextTypes - similar to how propTypes only is for validation

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

Use case:
I have a Portal component that renders its child into a div at the end of the body using ReactDOM-useful for fixed positioned components that you don't want to be in the stacking context of the parent. It works well until you have to pass down context because the context comes from an owner component not being rendered in the new HTML element

import React, { Children, PureComponent, PropTypes } from 'react';
import { unmountComponentAtNode, render } from 'react-dom';

// renders children at the end of the body
export default class Portal extends PureComponent {
  static propTypes = {
    children: PropTypes.node.isRequired
  };

  componentDidMount() {
    this._el = document.createElement('div');
    document.body.appendChild(this._el);

    this.renderIntoEl();
  }

  renderIntoEl = () => {
    const { children } = this.props;
    render(Children.only(children), this._el);
  };

  componentDidUpdate({ children }) {
    if (children !== this.props.children) {
      this.renderIntoEl();
    }
  }

  componentWillUnmount() {
    unmountComponentAtNode(this._el);
    document.body.removeChild(this._el);
  }

  render() {
    return null;
  }
}

I would like to be able to pass down all context available to Portal to the tree rendered in the body tag, something like this

import React, { Children, PureComponent, PropTypes } from 'react';
import { unmountComponentAtNode, render } from 'react-dom';

class ContextProvider extends PureComponent {
  static propTypes = {
    context: PropTypes.object,
    children: PropTypes.node.isRequired
  };

  getChildContext() {
    return this.props.context;
  }

  render() {
    return Children.only(this.props.children);
  }
}

// renders children at the end of the body
export default class Portal extends PureComponent {
  static propTypes = {
    children: PropTypes.node.isRequired
  };

  // we need to receive the context
  static contextTypes = {};

  componentDidMount() {
    this._el = document.createElement('div');
    document.body.appendChild(this._el);

    this.renderIntoEl(this.props.children, this.context);
  }

  renderIntoEl = (children, context) => {
    render(
      <ContextProvider context={context}>
        {Children.only(children)}
      </ContextProvider>,
      this._el
    );
  };

  componentWillReceiveProps({ children }, nextContext) {
    if (children !== this.props.children || nextContext !== this.context) {
      this.renderIntoEl(children, nextContext);
    }
  }

  componentWillUnmount() {
    unmountComponentAtNode(this._el);
    document.body.removeChild(this._el);
  }

  render() {
    return null;
  }
}

Activity

  1. changed the title [-]Need way to receive all context[/-] [+]Need way to receive and pass down all context (regardless of contextTypes/childContextTypes)[/+] on Nov 10, 2016
  2. gaearon commented on Nov 10, 2016

    @gaearon
    Collaborator

    You want unstable_renderSubtreeIntoContainer:

    import { unmountComponentAtNode, render, unstable_renderSubtreeIntoContainer } from 'react-dom';
    
    // ...
    
    export default class Portal extends PureComponent {
      static propTypes = {
        children: PropTypes.node.isRequired
      };
    
      // note: no need to receive context
    
      componentDidMount() {
        this._el = document.createElement('div');
        document.body.appendChild(this._el);
    
        this.renderIntoEl(this.props.children, this.context);
      }
    
      renderIntoEl = (children, context) => {
        unstable_renderSubtreeIntoContainer(
          this, // <---------- don't forget the first argument
          <ContextProvider context={context}>
            {Children.only(children)}
          </ContextProvider>,
          this._el
        );
      };
    
      // ...

    It's not a stable API but we'll keep it until we can offer a better way to do this.

  3. moodysalem commented on Nov 10, 2016

    @moodysalem
    Author

    @gaearon That worked for me, thank you

    What's the reason contextTypes are treated differently from propTypes in this regard?

    If portal is no longer receiving context, does React still know it has to re-render when context changes?

  4. gaearon commented on Nov 10, 2016

    @gaearon
    Collaborator

    If portal is no longer receiving context, does React still know it has to re-render when context changes?

    Yes, but in general relying on context updates is not recommended because there are significant problems (#2517) with the current implementation.

    What's the reason contextTypes are treated differently from propTypes in this regard?

    They were an ad-hoc API that wasn't really thought out. The idea is to limit the damage to encapsulation posed by context, but indeed relying on propTypes-like API here is a bit weird.

    Don't forget context is called "experimental" and the documentation recommends not to use it unless you really know why you're doing it.

  5. moodysalem commented on Nov 10, 2016

    @moodysalem
    Author

    I've read the thread you linked a bit

    This might be a little naive, so I'm not posting it on the main thread for that issue, but wouldn't having access to all the context regardless of contextTypes and childContextTypes resolve the issue of a middle component blocking render of a bottom component due to not knowing about context used by the children?

    That way the onus is on the person who defines a custom shouldComponentUpdate to determine whether its children are using context

  6. adidahiya commented on Jan 25, 2018

    @adidahiya

    I have a similar need for passing down arbitrary context without validation, but I can't use unstable_renderSubtreeIntoContainer because I need to mix React subtrees which use different major versions of React (I'm trying to incrementally migrate projects from React 15 to 16). Are there any other ways to do this @gaearon?

  7. gaearon commented on Jan 25, 2018

    @gaearon
    Collaborator

    I’m not quite sure what you’re asking so it’s hard to answer. You could wrap the whole child tree into a component that provides every context property that might be consumed by the tree below. Would that help? I don’t know, you know your constraints better than I do 🙂

  8. adidahiya commented on Jan 25, 2018

    @adidahiya

    Sorry for the lack of detail -- in short, I'm building a plugin framework which provides some utility React components for plugin hosts as well as plugin implementors. I'm trying to build a generic component which plumbs arbitrary context through a React tree "boundary" (where trees on different sides of the boundary can be on different major versions of React).

    You could wrap the whole child tree into a component that provides every context property that might be consumed by the tree below.

    Yeah, this does work, but ideally I'd like an implementation where I don't need to know all the possible context properties ahead of time.

    For now though, I think I can cover the majority of my use cases with a static set of keys (react-redux uses "store" and "storeSubscription" by default). Thanks for the quick response.

  9. adidahiya commented on Jan 26, 2018

    @adidahiya

    ^ follow up to that

    For now though, I think I can cover the majority of my use cases with a static set of keys (react-redux uses "store" and "storeSubscription" by default).

    This doesn't actually work since processChildContext doesn't work in React 16. It seems like React 16 doesn't know how to handle contexts constructed in React 15, so I am unable to mix trees while preserving context.

  10. gaearon commented on Jan 27, 2018

    @gaearon
    Collaborator

    In your example, the top level component providing context would have to be a React 16 component too. Context value is just an object. It doesn’t have a React version associated with it. But for sure mixing React versions in one tree won’t work.

  11. Tofandel commented on Dec 26, 2019

    @Tofandel

    A feature to get all the contexts (or at least their types/names) is a must have

    Sometimes you need to pass them to another framework/library (eg passing all contexts to vue provide in vuera)

    And the portal is not a one solution fits all deal.. (Because it doesn't fit this one use case)

    So adding this to current api would be nice..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions