F
F
frw232020-01-16 23:06:03
React
frw23, 2020-01-16 23:06:03

How to create a component whose props will immediately fall into the props of all the underlying components?

Styled-components has a provider called ThemeProvider, it sets the theme={theme} prop. This prop is then directly available in all internal components. How to implement such a provider yourself?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
camelCaseVlad, 2020-01-17
@camelCaseVlad

Hello, some time ago I wrote an article on this topic on Habré, here is the link:
https://habr.com/ru/post/462963/
If you are using a react version higher than 16.8, replace theme-context/context.js in code on

import React from 'react';

const { Provider, Consumer } = React.createContext({});

export { Provider, Consumer };

F
frw23, 2020-01-17
@frw23

camelCaseVlad , Your solution is almost exactly what you need, but you still have to use Consumer in your own components.

function MyComponent() {
  const renderMyComponent = theme => {
    return (
      // code
    );
  };
  return <ThemeConsumer>{theme => renderMyComponent(theme)}</ThemeConsumer>;
};

ThemeProvider does it somehow under the hood, I want to understand how. All that remains is to import MyProvider at the top level, specify the props there and that's it. This prop automatically gets into all components without additional actions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question