Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a pariticular fileExists in reactjs

Tags:

reactjs

I am developing an app in React js, I'm having an issue to check whether a particular file exists in the directory or not. Actually I have a header component i.e Header.js and its a common header. But for some clients I have to change the header according to their requirements. I've to do this by making a folder with client's id and then store new header component for that client in that directory. Now I've to check on run time if a header for a specific client exists then show that client's specific header else the common header. I also have to make some other client specific components i.e footer, aside or section etc. for some specific specific clients according to their requirements. But I'm unable to check in react whether a specific component/file exists or not??

like image 883
Majid NWL Avatar asked Jan 15 '18 08:01

Majid NWL


People also ask

How to check if a file already exists in JavaScript?

The exists() method of the File object returns a boolean value based on the existence of the file in which it was invoked. If the file exists, the method returns true. It returns false if the file does not exist.


1 Answers

You can try to require your file and then depending on the result display the correct component.

const tryRequire = (path) => {
  try {
   return require(`${path}`);
  } catch (err) {
   return null;
  }
};

Then to use it :

render() {
 const Header = tryRequire('yourPath') ? tryRequire('yourPath').default 
   : DefaultHeader;

 return (
   <Header />
 );
}

There is another way using React.lazy but to do so you will need to create a component that is located at to root of your project (if you are using Create React App it will be placed at ./src/DynamicImport.js).

Here's the logic:

import React, { Suspense, useState, useEffect, lazy } from 'react';

const importCompo = (f, defaultComponentPath) =>
  lazy(() =>
    import(`./${f}`).catch((err) => {

    // Simulate behaviour in Strapi
    // Lazy only support default export so there's a trick to do here 
       when using a library that does not have a default export
    // The example here uses the strapi-helper-plugin package
    if (defaultComponentPath === 'strapi-helper-plugin') {
      return import('strapi-helper-plugin').then((module) => {
        const { Button } = module;

        return {
          // Here's the trick
          // I am creating a new component here
          default: () => <Button primary>Something</Button>,
        };
      });
   }

  return import(`${defaultComponentPath}`);
 }),
);

const DynamicImport = ({ filePath, defaultComponentPath, ...rest }) => {
  const [module, setModule] = useState(null);

  useEffect(() => {
    const loadCompo = () => {
      const Compo = importCompo(filePath, defaultComponentPath);

      setModule(<Compo {...rest} />);
    };

    loadCompo();
  }, []);

  return <Suspense fallback="loading">{module}</Suspense>;
};

DynamicImport.defaultProps = {
  // defaultComponentPath: './components/DefaultCompo',
  defaultComponentPath: 'strapi-helper-plugin',
};

export default DynamicImport;

Then to use it:

const MyCompo = props => {
  return (
    <DynamicImport
      filePath="./components/Foo"
      defaultComponentPath="./components/DefaultCompo"
    />
  );
};
like image 90
soupette Avatar answered Oct 08 '22 00:10

soupette