Search code examples
reactjsremix

Access .env variables in .mdx file | Remix


What is the best way to access environment variables in a .mdx file. Remix's approach to accessing .env variables in a normal component is to use the loader data hook (useLoaderData()). However, hooks cannot be used so easily in .mdx files. I also tried passing the environment variables via props from the parent component, but that didn't work either, as I couldn't figure out which library Remix uses to work with .mdx files. cheers


Solution

  • I couldn't figure out how to pass the props to the Component, but I found a somewhat good workaround. I created a ContactText component whose only task is to read the contactConfig and return the desired config property value.

    ContactText.tsx

    const ContactText: React.FC<TProps> = (props) => {
      const { contactConfig } = useRootContext();
      const { contactConfigPath, as, ...rest } = props;
    
      const getValue = React.useCallback((): string => {
        const contactConfigPathParts = contactConfigPath.split('.');
        let currentValue = contactConfig;
        for (const part of contactConfigPathParts) {
          if (currentValue != null) {
            currentValue = (currentValue as any)[part];
          }
        }
        return typeof currentValue === 'string' ? currentValue : 'unknown';
      }, [contactConfig, contactConfigPath]);
    
      return as != null ? (
        React.createElement(as, {
          children: getValue(),
          ...rest,
        })
      ) : (
        <>{getValue()}</>
      );
    };
    
    export default ContactText;
    
    type TProps = {
      contactConfigPath: string;
      as?: React.ElementType;
    };
    

    whatever.mdx

    // ..
    
    
    Phone: <ContactText contactConfigPath={'phoneNumber'} />
    
    <ContactText contactConfigPath={'address.postCode'} />
    
    // ..