D3athSpank D3athSpank - 1 month ago 7
React JSX Question

Combining components to one library

Im currently creating a UI library for my react native project.
The components are separated into its own files like: Button, TextBox, Panel etc etc

So when i want to use them I do:

import Button from '../UI/button';
import TextBox from '../UI/textBox';


But how could I impletement the following call instead? Not needing to do import statetments for each specific component.

import { Button,TextBox, SomeOtherComp } from '../UI/??';


This would save a lot of typing when I want to use multiple components...

Answer

Create a file called index.js

The purpose of this file is to simple expose all available components from your library

import Button from './button';
import TextBox from './textBox';
...

module.exports = {
  Button,
  TextBox,
  ...
};

In the code that consumes your UI library, you can now import the components like this:

import { Button, TextBox, SomeOtherComp } from '../UI';

When you import a folder name, the packages will look for an index.js file and import that.

Comments