Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share React Components between projects

Tags:

npm

reactjs

I built a Component that I want to use in separate projects. What is the simplest best way to reuse this Component across projects using NPM?

like image 520
Alex Bollbach Avatar asked Sep 11 '17 04:09

Alex Bollbach


People also ask

How do you share data between two React components?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.


1 Answers

You haven't indicated whether you wish to keep this component private, so I'm going to answer two ways:

If you are going to open-source your component

This is easiest: publish your component(s) as an npm package (see the docs here). Then install your package just like any other in the projects where you will be using your components.

If you wish to keep it private

You have several options here:

  1. pay for a private modules on npm (docs here). If you go this route, you can install your package just like any other.

  2. Use npm link (docs) to create a link from the project(s) to the component package located on your local storage. This works but is kind of tricky to set up. The benefit of this is that if you rebuild your component, all projects with a link to the component will see those changes immediately.

  3. Use npm install to install from your (private) Github or other repository. This works similarly to the normal npm install and is a little easier to use than npm link. The downside is that any changes to the component need to be pushed to the remote repository and then the project(s) using the component need to be updated.

like image 93
Kryten Avatar answered Oct 03 '22 20:10

Kryten