How to Create a React Module — an Actual Example

Hello to everyone out there who wants to know all about creating a React module. The React component module I created was for Google Material Icons. (https://www.npmjs.com/package/react-google-material-icons) .

To create this module, I followed the below post which worked fine for me. In case you feel like reading more on it, I would suggest you to read this post.

https://medium.com/@jbscript/developing-react-components-and-libraries-with-nwb-2018059ea25a

Let’s get started, peeps!

View story at Medium.com

Prerequisites

Of course, you need to have Nodejs and npm installed. 😎

Install nwb globally

Create the project

Here, the last argument is the project name and it will create a directory name with the above project name and all the required files under it. This will then generate some questions and what I did was to respond with ‘yes’ for ‘Es6 bundles’ and ‘UMD build for global usage’. If you enable UMD build, it will allow you to use the module with the global variable which will ask the next question. I added ‘ReactGoogleMaterialIcons’ as my UMD build set.

Now the project is almost ready. It’s just a matter of doing your codes. 🙂 If you want to confirm the setup before start coding, just run npm install & then npm start . It will open up the application in the browser.

The code

I added the main.css file under src. Then I imported the Google Material font from their CDN in the css file itself.

Next, import it in the index.js and put the jsx code as below.

The user can provide 2 properties to the module: the icon and its size. However, the size is an optional parameter (default is 24).

Note

I added ‘ — copy-files’ flag into build script in the package.json file because otherwise, the final build will not work since the default configuration does not copy the css file into ‘es’ and ‘lib’ directories.

In order to check the module, we have to write a test, under the directory called ‘demo’. In the index.js file, which is under the directory ‘demo’, I imported my module (index.js file which is under the directory ‘src’) and wrote few test cases.

That’s it. Let’s run the code.

First, run the command npm install if you haven’t run that before. Then run npm start . If everything is okay, you will get the following result.

Publishing to npm

Run npm run build command to build the package. Then run the command npm publish .

Leave a Comment

Your email address will not be published. Required fields are marked *