Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing react components across projects

Tags:

npm

reactjs

I want to split my web project into three: front-end, back-end and super-admin.

What is the best way to re-use the components across code bases? Npm packages? That seems hard to maintain:

  1. Open component dev package
  2. Make changes
  3. Push changes
  4. Tag version
  5. Update all projects

Seems complex and prone to errors. Is there a better way?

like image 394
AndrewMcLagan Avatar asked Mar 17 '16 20:03

AndrewMcLagan


People also ask

How do you reuse components in React?

First we have to import the component into where we want to reuse it, as you can see in the first line of the above code where we have our import statement. Second, because we passed in name and imageUrl as props in the author component earlier, the author component expects the same data to be passed into it at first.

Is component reusability available in react JS?

In React, a reusable component is a piece of UI that can be used in various parts of an application to build more than one UI instance. For instance, we can have a Button component that displays different texts on different pages.

How can we achieve reusability in React?

Solution: We can use a custom hook that will allow us to reuse this toggle logic in both components, and in any new component added in the future.

Does React re render entire component?

By default, all descendants of a component will re-render if that component's state changes.


1 Answers

Depends on if you need to use different versions of the shared components from different projects. If so, you probably need to make a versioned npm package. However, if you just want to share the packages and use the same version everywhere, you have other options. For one, you don't have to actually build and publish an npm packge, you can just use npm link. This will basically create a symlink to your shared code in node_modules of the other projects.

Alternatively, you can do it without any npm package at all, just have the shared components in a separate project (directory) and import them in javascript through an alias, using a bundling system (webpack alias / browserify aliasify).

like image 159
Vladimir Rovensky Avatar answered Oct 03 '22 06:10

Vladimir Rovensky