Context in "stateless" component?

Viewed 28535

I have the following code in a component and I would like a stateless component to access this part of code:

Main component:

function createApp(store, communityIds) {
const App = React.createClass({

    childContextTypes: {
        localizedString: React.PropTypes.func,
    },

    getChildContext: function() {
        return {
            localizedString: function(key, fallback) {
                return getKey(key, fallback);
            },
        };
    },

    render: function() {
        return (
            <Provider store={store}>
                <Client communityIds={communityIds}/>
            </Provider>
        );
    },
});

return <App/>;
}

Stateless:

export default () => (dispatch, getState) => {
    const state = getState();

    const token = state.user.get('token');

    if (!token) {
        throw new Error('test'); // this.context.localizedString does not work
    }
}
5 Answers

I had the same question, but was on Expo SDK 32, meaning I don't have access to hooks.

Here's how I achieved it:

import { reduxForm } from 'redux-form'
import { ReduxFormContext } from 'redux-form/lib/ReduxFormContext'

const ShowFormName = () => (
  <ReduxFormContext.Consumer>
    {
      ({ form }) => <Text>{form}</Text>
    }
  </ReduxFormContext.Consumer>
)

export default reduxForm({ form: 'formName' })(ShowFormName)
Related