0

So I need to access to the value of context without calling it as a render function.

NOT Like this:

const Child = () => {
  return (
    <ThemeConsumer>
      {context => {return <Text>{context}</Text>}}
    </ThemeConsumer>
  );
};

I have this so far:

import React from 'react';
export const ThemeContext = React.createContext(0);
export const ThemeProvider = ThemeContext.Provider;
export const ThemeConsumer = ThemeContext.Consumer;

And I am using the provider like this:

  render() {
    const { index } = this.state;
    return (
      <ThemeProvider value={index}>
        <TabView
          key={Math.random()}
          navigationState={this.state}
          renderScene={this.renderScene}
          renderTabBar={this.renderTabBar}
          onIndexChange={this.handleIndexChange}
        />
      </ThemeProvider>
    );
  }

Is that ok?

The main issue I have so far is that where I need that value, is not a class nor a functional component.

I need to do something like this:

import { ThemeConsumer } from '../../context/BottomNavigationTheme';
import HomeScreen from '../screens/HomeScreen';
import HomeScreen2 from '../screens/HomeScreen2';

functionToGetContextValue = () => valueFromContext;

const HomeStack = createStackNavigator({
  Home: functionToGetContextValue ? HomeScreen : HomeScreen2, // HERE I NEED IT
});

HomeStack.navigationOptions = {
  tabBarLabel: 'All Passengers',
  tabBarIcon: ({ focused }) => <AllPassengersIcon focused={focused} />,
};

export default createBottomTabNavigator({
  HomeStack,
  LinksStack,
  SettingsStack,
});

What should I do to access to that value?

Reacting
  • 3,765
  • 4
  • 24
  • 56

1 Answers1

0

You can with HOC. Create a function withTheme

export const withTheme = Component => props => (
  <ThemeConsumer>
    {context => <Component {...props} them={context} />
  </ThemeConsumer>
) 

Then use in any child component you want.

class TabView extends React.PureComponent {
  componentDidMount() {
    console.log(this.props.theme)
  }
  ...
}

export default withTheme(TabView)

A working Context with HOC is here https://codesandbox.io/s/o91vrxlywy

If you use React hooks (ver 16.8) you can use useContext API https://reactjs.org/docs/hooks-reference.html#usecontext

Giang Le
  • 4,160
  • 1
  • 19
  • 20