React: [Feature Request] "PropsProvider" to inject props into all child components

Created on 28 Jul 2019  路  2Comments  路  Source: facebook/react

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

What is the current behavior?
Nothing

What is the expected behavior?
Supply a method to inject props into all children components below declaration.

const globalProps = {
    everywhere: 'Hello world!'
}

ReactDOM.render(
    <PropsProvider value={globalProps}>
        <App />
    </PropsProvider>
)
const A = ({ everywhere }) => <div>{everywhere}</div>

const App = ({ everywhere }) => <div>
    <p>{everywhere}</p>
    <A />
</div>

Most helpful comment

So every single descendant of a PropsProvider would have the extra props spread on top of its existing props? That seems to make proper encapsulation impossible: After adding a PropsProvider, if I put a third party component anywhere in my tree that, as a part of its own internal implementation, uses a prop name that I also happened to use in my PropsProvider, I've broken it.

It's the same nameclashing problem as heavily nested HoCs that each spread some extra value onto props before passing them down.

All 2 comments

So every single descendant of a PropsProvider would have the extra props spread on top of its existing props? That seems to make proper encapsulation impossible: After adding a PropsProvider, if I put a third party component anywhere in my tree that, as a part of its own internal implementation, uses a prop name that I also happened to use in my PropsProvider, I've broken it.

It's the same nameclashing problem as heavily nested HoCs that each spread some extra value onto props before passing them down.

Naming clashes could be dealt with in the same way that naming clashes are dealt with in similar circumstances which occur in other languages with shared anonymised context (like Go or Node+Express).

Library vendors could simply use a naming convention like

{ __MY_LIB_DATA__: { ...myLib-state } }

and/or could provide a getter function to use with your functions

const getMyLib = props => props.__MY_LIB_DATA__ 

const MyComponent = (props) => {
    const myLibData = getMyLib(props)
    return <div>Hi</div>
}

Ultimately, the intention is to provide IoC where the existing React tooling does not satisfy

Was this page helpful?
0 / 5 - 0 ratings