Skip to content Skip to sidebar Skip to footer

Is It Possible To Pass Context Into A Component Instantiated With Reactdom.render?

TL;DR Given the following example code: ReactDOM.render(, someDomNode); Is it possible to manually pass React context into the instance of MyC

Solution 1:

No. Before react 0.14 there was method React.withContext, but it was removed.

However you can do it by creating HoC component with context, it would be something like:

importReactfrom'react';

functioncreateContextProvider(context){
  classContextProviderextendsReact.Component {
    getChildContext() {
      return context;
    }

    render() {
      returnthis.props.children;
    }
  }

  ContextProvider.childContextTypes = {};
  Object.keys(context).forEach(key => {
    ContextProvider.childContextTypes[key] = React.PropTypes.any.isRequired; 
  });

  returnContextProvider;
}

And use it as following:

constContextProvider = createContextProvider(context);

ReactDOM.render(
  <ContextProvider><MyComponentprop1={someVar} /></ContextProvider>,
  someDomNode
);

Solution 2:

In React 15 and earlier you can use ReactDOM.unstable_renderSubtreeIntoContainer instead of ReactDOM.render. The first argument is the component who's context you want to propagate (generally this)

In React 16 and later there's the "Portal" API: https://reactjs.org/docs/portals.html

Post a Comment for "Is It Possible To Pass Context Into A Component Instantiated With Reactdom.render?"