You can use the React context it provides a way to pass data through the component tree without having to pass props down manually at every level.
First, you have to create the React Context itself which gives you access to a Provider and Consumer component. When you create the context with React by using createContext, you can pass it an initial value. The initial value can be null too.
Please have a look as below:
// src/ThemeContext.js import React from 'react'; const ThemeContext = React.createContext(null); export default ThemeContext;
Second, component A would have to provide the context with the given Provider component. In this case, its value is given to it right away, but it can be anything from the component state (e.g. fetched data) to props. If the value comes from a modifiable React State, the value passed to the Provider component can be changed too.
// src/ComponentA.js import React from 'react'; import ThemeContext from './ThemeContext'; const A = () => ( <ThemeContext.Provider value="green"> <D /> </ThemeContext.Provider> );
Component A displays only component D, doesn't pass any props to it though, but rather makes the value green available to all the React components below. One of the child components will be component C that consumes the context eventually.
Third, in your component C, below component D, you could consume the context object. Notice that component A doesn’t need to pass down anything via component D in the props so that it reaches component C.
// src/ComponentC.js import React from 'react'; import ThemeContext from './ThemeContext'; const C = () => ( <ThemeContext.Consumer> {value => ( <p style={{ color: value }}> Hello World </p> )} </ThemeContext.Consumer> );
The component can derive its style by consuming the context. The Consumer component makes the passed context available by using a render prop. As you can imagine, following this way every component that needs to be styled according to the theme could get the necessary information from React's Context by using the ThemeContext's Consumer component now. You only have to use the Provider component which passes the value once somewhere above them.
screenPropsto send data accross different components