Home > Software design >  Why do I get a missing <Text> error when using react context?
Why do I get a missing <Text> error when using react context?

Time:04-04

Why does my implementation of creating and using a react context result in this error related to Text?

Here is the component in which I specify the context as a wrapper component.

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';

import SignInScreen from '../screens/SignInScreen';
import SignUpScreen from '../screens/SignUpScreen';
import ConfirmEmailScreen from '../screens/ConfirmEmailScreen';
import ForgotPasswordScreen from '../screens/ForgotPasswordScreen';
import NewPasswordScreen from '../screens/NewPasswordScreen';
import { SimpleContextProvider } from '../contexts/SimpleContext';

const Stack = createStackNavigator();

export default function LoginStack(props) {
  return (
    <SimpleContextProvider>
      <Stack.Navigator mode="card" screenOptions={{ headerShown: false }}>
        <Stack.Screen name="SignIn" component={SignInScreen} />
        <Stack.Screen name="SignUp" component={SignUpScreen} />
        <Stack.Screen name="ConfirmEmail" component={ConfirmEmailScreen} />
        <Stack.Screen name="ForgotPassword" component={ForgotPasswordScreen} />
        <Stack.Screen name="NewPassword" component={NewPasswordScreen} />
        <Stack.Screen name="App" component={AppStack} />
      </Stack.Navigator>
    </SimpleContextProvider>
  );
}

Here is my simple context file... SimpleContext.js

import * as React from 'react';
const SimpleContext = React.createContext();

const SimpleContextProvider = ({children}) => {
  return <SimpleContext.Provider value={1}> {children} </SimpleContext.Provider>;
};

const useSimple = () => React.useContext(SimpleContext);
export { SimpleContextProvider, useSimple };

Why do I see this error?

Text strings must be rendered within a component? I do not see any stray strings that are not wrapped in a component. If I remove the SimpleContextProvider, this error goes away.

In the name of a complete description, I am wrapping the context around navigation screens. Maybe this matters.

CodePudding user response:

You have spaces around the children. These are in the middle of a line, and thus they will be treated as spaces in the output. Ie, this: > {children} < needs to be this >{children}<. Alternatively, if you split it onto multiple lines it would work, because whitespace at the start and end of lines is ignored:

return (
  <SimpleContext.Provider value={1}>
    {children}
  </SimpleContext.Provider>
)
  • Related