How to create a component that imports static content?

63 Views Asked by At

I would essentially like to do this:

import React from 'react';
import CodeBlock from '@theme/CodeBlock';

export function MyCode({fileName}) {
  const rawText = import('!!raw-loader!@site/static/' + fileName);  
  return <CodeBlock'>
    {rawText}
  </CodeBlock>
}

But it doesn't work because import returns a promise, which in turn requires the function to become async which then fails to be a regular React component. Is there a way to make this work?

1

There are 1 best solutions below

0
On

You can try something like this:

export function MyCode({fileName}) {
  const [loadingText, setLoadingText] = setState(true)

  async function getRawText(){
    const text = await import('!!raw-loader!@site/static/' + fileName)
    setLoadingText(false)

    return text
  }
  return <CodeBlock'>
    {loadingText ? 'Loading text...' : getRawText()}
  </CodeBlock>
}