How to Share React Components Between NextJS Projects

Publishing React components from a NextJS Project, to reuse in another.

Nathan Sebhastian
Bits and Pieces

--

Next.js is the most popular React framework for developing React server-side rendering apps.

This tutorial will help you to develop reusable React components that can be shared across different projects and repositories by using Bit platform.

Bit is a composable software development platform that enables you to build, share and reuse components between different projects and repositories. It’s a very handy tool that allows you to build apps with independently-versioned containers of code called Bit Components.

Creating a reusable card list component

We’re going to create a simple card list component that you can use to display posts in a neat and organized layout. You can see a demo of the final result here.

These components will be styled using styled-components. We will isolate the button and the card into its own component so that it can be used separately outside of a card list:

A simple card list component, made up of a card and a button component

Before getting started, please make sure that you have Node.js version 10.3 or later installed on your computer. Let’s install a fresh new Next application by using the terminal:

npx create-next-app
# or
yarn create next-app

Inside your Next directory, create a new directory named components/ that will host all of your reusable components.

It’s time to develop our components. We’re going to start with developing the StyledButton component. It’s a simple component with props for Title and onClick function:

import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
const Button = styled.button`
cursor: pointer;
background: #DB7093;
color: white;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid #DB7093;
border-radius: 3px;
&:hover{
background: #C16482;
border: 2px solid #C16482;
}
`;
const StyledButton = ({
title,
onClick,
}) => (
<Button onClick={onClick}>{title}</Button>
)
StyledButton.propTypes = {
/**
* button title
*/
title: PropTypes.string.isRequired,
/**
* on click function
*/
onClick: PropTypes.func.isRequired,
};
export default StyledButton;

Next, we need to write the StyledCard component that makes use of the StyledButton component. This component will have image, title, date, and description props that will be rendered as a card.

We will pass the StyledButton’s title and onClick props through this component using the buttonTitle and buttonClick props:

import React from 'react'
import styled from 'styled-components'
import PropTypes from 'prop-types'
import StyledButton from '../StyledButton'
const StyledContainer = styled.div`
border: 1px solid #C16482;
padding: 25px 12px 18px;
margin: 25px 20px;
};
`
const StyledImg = styled.img`
width: 100%;
height: 100%;
object-fit: cover;
border: 1px solid #C16482;
`
const Title = styled.h2`
color: #C16482;
font-weight: 300;
@media (max-width: 500px) {
font-size: 1rem;
}
`
const Date = styled.div`
color: #ccc;
font-weight: 300;
margin: 6px 0;
@media (max-width: 500px) {
font-size: 0.8rem;
}
`
const Description = styled.p`
color: #C16482;
font-weight: 300;
@media (max-width: 500px) {
font-size: 0.75rem;
}
`
const StyledCard = ({
image,
title,
date,
description,
buttonTitle,
buttonClick
}) => (
<StyledContainer>
<StyledImg src={image} />
<Title>{title}</Title>
<Date>{date}</Date>
<Description>{description}</Description>
<StyledButton title={buttonTitle} onClick={buttonClick} />
</StyledContainer>
)
StyledCard.propTypes = {
/**
* post image
*/
image: PropTypes.string.isRequired,
/**
* post title
*/
title: PropTypes.string.isRequired,
/**
* date
*/
date: PropTypes.string.isRequired,
/**
* short description of the post
*/
description: PropTypes.string.isRequired,
/**
* Title for the button
*/
buttonTitle: PropTypes.string.isRequired,
/**
* on click function for the button
*/
buttonClick: PropTypes.func.isRequired,
};
export default StyledCard

Finally, we’ll use the StyledCard inside the StyledCardList component. This component will take a single array prop containing the list of posts that are going to be rendered by the component:

import React from 'react';
import styled from 'styled-components'
import PropTypes from 'prop-types';
import StyledCard from '../StyledCard';
const StyledContainer = styled.div`
max-width: 750px;
padding: 50px 12px;
width: 100%;
margin: auto;
`
const StyledCardList = ({postList}) => {
return (
<StyledContainer>
{postList.map(post => (
<StyledCard
key={post.id}
image={post.image}
title={post.title}
date={post.date}
description={post.description}
buttonTitle={post.buttonTitle}
buttonClick={post.buttonClick}
/>
))}
</StyledContainer>
);
};
StyledCardList.propTypes = {
/**
* A list of posts to render
*/
postList: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number,
image: PropTypes.string,
title: PropTypes.string,
date: PropTypes.string,
description: PropTypes.string,
buttonTitle: PropTypes.string,
buttonClick: PropTypes.func,
})
),
};
export default StyledCardList;

You can test the StyledCardList component by providing it with dummy data and rendering it inside pages/index.js:

const postList = [
{
id: 1,
image: "https://picsum.photos/id/134/300/200",
title : "My First Post",
date : "06/26/2020",
description : "This is my first post. Hello World!",
buttonTitle : "Read this post",
buttonClick : () => alert("This should take you to the post link")
},
{
id: 2,
image: "https://picsum.photos/id/5/300/200",
title : "My Second Post",
date : "06/27/2020",
description : "This is my second post. Keep up the rythm!",
buttonTitle : "Read this post",
buttonClick : () => alert("This should take you to the post link")
}
]
// render the postList into StyledCardList component<StyledCardList postList={postList} />

Now that we have our components sorted out, we can start publishing our components to the Bit platform to allow other projects to reuse it.

Registering components to Bit

In order to start publishing components to Bit, you need to register a free account. Once registered, create a new collection to save your components into:

Create a “new” collection

A collection is just a simple way to group your components together. For example, you may have a collection of components for developing a chat application. You’re also able to set the privacy settings in the collection to public or private.

Let’s start publishing our components to Bit. Open your terminal and install the Bit terminal tool:

npm install bit-bin --global

Once the install is finished, head back to your Next project’s terminal and initialize a new Bit workspace:

bit init

This command will generate the following resource for you:

  • Bit workspace configuration inside package.json
  • Components bitmap with .bitmap file

In your package.json file, you’ll see a new bit config similar to this:

"bit": {
"componentsDefaultDirectory": "components/{name}",
"packageManager": "npm"
}

Next, you need to login to your Bit account from the terminal:

bit login

The command above will open a new window where you can log in to your Bit account. Once logged in, you’re ready to publish your components.

To start the publishing process, add your components using the bit add command:

bit add components/*

You can review components you’ve tracked on Bit, but please don’t publish them just yet:

bit status

Before you publish the components, you need to make sure that these components are consumable by other projects and have no error. You can do that by building these components using Bit compiler for React:

bit import bit.envs/compilers/react --compiler
bit build

Bit’s React compiler will build your components in an isolated environment to make sure the build will also succeed on the cloud or in any other repository.

Once the build is done and you have no error, you can tag your components as ready to publish. For example:

bit tag --all 0.0.1

The command will tag all tracked components as ready to publish as version 0.0.1. If you omit the version, Bit will simply tag the closest next version of your components.

Alright, now that we have the components tagged, let’s publish them to a Bit collection by using the bit export command and the full name of the collection, structured as <username>.<collection>:

bit export nsebhastian.post-card-components

Once done, you can visit the bit.dev website and see your components published inside the collection you’ve created earlier.

If you click on one of the components, you’ll see that Bit has a playground that renders the component, so you can see how the component works without needing to download and install it locally:

Example Bit playground

Bit also detects the use of prop-types in your React code and generate a documentation based on it. You can see the documentation just below the playground:

Documentation generated by Bit

You can also improve the documentation by writing the documentation in JSdocs format or adding a markdown file for your components.

Now that your components are published on Bit, you’re ready to reuse them in other React-based projects aside from NextJS, including projects that use Gatsby or Electron. Just install the component using your favorite package manager:

npm i @bit/nsebhastian.post-card-components.styled-card-list
#or
yarn add @bit/nsebhastian.post-card-components.styled-card-list

And import the component inside your application:

import StyledCardList from '@bit/nsebhastian.post-card-components.styled-card-list';const App = () => {
return(
<StyledCardList postList={postList} />
)
}

If you’d like to import other people’s components and customize them to fit your needs, you can do so by using the bit import command. Notice how the format is different from installing with package managers:

bit import nsebhastian.post-card-components/styled-card-list

The component will be installed in the components/ directory by default. Here is the link to the completed Next.js app repo.

Conclusion

You’ve learned how to publish and share React components into Bit platform. Once published, you can reuse those components in another project by installing them through your favorite package manager or Bit. Very neat!

Bit is a handy development tool that helps you to track, publish, and install components with simple terminal commands similar to Git and NPM. By using Bit, you can develop your application faster by reusing components that have been developed by others and even collaborate to improve the components.

Learn More

--

--

Web Developer and Writer. Sharing what I learn on productivity and success.