DEV Community

Cover image for How to create reusable React Components across your projects with bit.dev
Mike Lu
Mike Lu

Posted on • Updated on

How to create reusable React Components across your projects with bit.dev

React is one of the most popular JavaScript libraries for building user interfaces. One of the key benefits of React is its component-based architecture, which allows developers to create reusable UI components that can be shared across different projects.

Bit.dev is a platform that makes it easy to create and share React components.

There are several reasons why someone might need to use Bit.dev for their React components:

  1. Reusability: Bit.dev allows developers to create and share reusable components across different projects and teams. This can greatly reduce development time and ensure consistency across projects.
  2. Collaboration: Bit.dev provides tools for testing, versioning, and collaboration, making it easy for teams to work together on component development. This can help to improve code quality and reduce errors.
  3. Scalability: Bit.dev is a distributed and scalable platform that can handle large-scale component-based development workflows. It provides a flexible and customizable workflow that can be adapted to the specific needs of different projects and teams.
  4. Open-source community: Bit.dev has a thriving open-source community that contributes to the platform and creates new components. This can be a great resource for developers looking for inspiration or looking to contribute to open-source projects.
  5. Integration: Bit.dev can integrate with other tools and platforms, such as Git and CI/CD pipelines, to create a seamless development workflow. This can help to streamline development processes and improve overall efficiency.

In this blog, I'll explain to you the steps to create and deploy React components with Bit.dev.

In order to start creating components using bit, first you need to create an account on bit.cloud.

Step 1: Login to the bit.cloud, create your own scope where you will deploy your components in the dashboard.

Step 2: Install bit on your machine. Follow the below commands.

  • Install bvm (bit version manager).
npm i -g @teambit/bvm
Enter fullscreen mode Exit fullscreen mode
  • Ensure of installed bit on your machine.
bvm --version
Enter fullscreen mode Exit fullscreen mode

Refer to this troubleshooting if it's not working.

Step 3: Init your components bit project
Create new workspace by running.

bit new react tasks-workspace --default-scope my-org.tasks-scope
Enter fullscreen mode Exit fullscreen mode

Here, tasks-workspace means Workspace name, my-org means Organization / username, and tasks-scope means default scope for the new components.
It will create a new workspace with components as a default scope.

Step 4: Create your first component.
You have to create your own components inside tasks-workspace you just created.
Therefore, run the following command.

cd tasks-workspace
Enter fullscreen mode Exit fullscreen mode

Then you can run the following command to create the new component.
Here, for example, let me create the button component.

bit create react button
Enter fullscreen mode Exit fullscreen mode

This will create a button component within components folder.
The created component will have the following files

index.ts: Entry component file.
button.tsx: Boiler plate for creating component.
button.spec.tsx: A file to write tests.
button.docs.mdx: A documentation file.
button.composition.tsx: A file for testing different variations of the component per creator's choice.

To start the development server on your local and preview the component you created, you can run the following command.

bit start
Enter fullscreen mode Exit fullscreen mode

Start editing the button component and preview changes on the browser.

In the component folder, you can create multiple files such as stylesheet files, and components files to support the main component. For now, let's just make a button component work.

import React, { ReactNode } from 'react';

export type ButtonProps = {
  /**
   * a node to be rendered in the special component.
   */
  children?: ReactNode;
  /**
   * Onclick event
   */
  onClick?: () => void
};

export function Button({ children, onClick }: ButtonProps) {
  return (
    <button onClick={onClick}>
      {children}
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Let's create two more components, title, and input to complete a form with a title, inputs, and a button.

Run following 2 commands.

bit create react input
Enter fullscreen mode Exit fullscreen mode
bit create react title
Enter fullscreen mode Exit fullscreen mode

On title.tsx file in title folder add this code.

import React, { ReactNode } from 'react';

export type TitleProps = {
  /**
   * a node to be rendered in the special component.
   */
  children?: ReactNode;
};

export function Title({ children }: TitleProps) {
  return <h1>{children}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

and on input.tsx in input folder add this code.

import React, { CSSProperties, ChangeEvent } from 'react';

export type InputProps = {
  /**
   * label text
   */
  label: string;
  /**
   * input id
   */
  id?: string;
  /**
   * input type
   */
  type?: string;
  /**
   * on input change
   */
  onChange: (value: ChangeEvent<HTMLInputElement>) => void;
  /**
   * input value
   */
  value: string;
  /**
   * input style style
   */
  style?: CSSProperties;
};

export function Input({ label, id, type, onChange, value, style }: InputProps) {
  return (
    <label>
      <div>{label}</div>
      <input
        id={id}
        style={style}
        onChange={onChange}
        value={value}
        type={type}
      />
    </label>
  );
}
Enter fullscreen mode Exit fullscreen mode

and on the input.composition.tsx add the following cpde.

import React, { useState } from 'react';
import { Input } from './input';

export const BasicInput = () => {
  const [value, setValue] = useState('');
  return (
    <Input
      label="Email"
      type="email"
      onChange={(e) => setValue(e.target.value)}
      value={value}
    />
  );
};
Enter fullscreen mode Exit fullscreen mode

Test these components you created on the live preview.

Step 5: Add test on the components.
bit uses jest under the hood to run react tests.

Step 6: Use created components within your components project before deployment.
With bit, we can import other components within our components without deploying the library.
Let's look at how can do it.

From the above created components, let's create a form component named login which will include email and password inputs, submit button, and title.

Run the following command.

bit create react login
Enter fullscreen mode Exit fullscreen mode

and on login.tsx, add the following code.

import React, { useState } from 'react';
import { Input } from '@tasks-scope/components.input';
import { Title } from '@tasks-scope/components.title';
import { Button } from '@tasks-scope/components.button';

export type LoginProps = {
  onSubmit: (data: { email: string; password: string }) => void;
};

export function Login({ onSubmit }: LoginProps) {
  const [data, setData] = useState({
    email: '',
    password: '',
  });
  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        onSubmit(data);
      }}
    >
      <Title>Welcome Back</Title>
      <Input
        value={data.email}
        onChange={(e) =>
          setData({
            ...data,
            email: e.target.value,
          })
        }
        label="Email"
      />
      <Input
        value={data.password}
        onChange={(e) =>
          setData({
            ...data,
            password: e.target.value,
          })
        }
        label="Password"
      />
      <Button>Submit</Button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now we have a working form component built with three other components.

Step 7: Install packages.
There will be times when you will want to create a component but that component will need an external package to work, for instance, one might need a styled-components package to create a component.

In this case, run the following command.

bit install styled-components
Enter fullscreen mode Exit fullscreen mode

Step 8: Deploy your components.
To deploy your lib you need to login to bit using CLI.
Run the following command.

bit login
Enter fullscreen mode Exit fullscreen mode

This will open the browser and give you access to deploy your library. Before deploying we need to tag all your components.
Tagging components assigns new versions to our components.

Run the following command.

bit tag [tag name]
Enter fullscreen mode Exit fullscreen mode

In .bitmap, we should see the new versions assigned to our new components.

To deploy the components, you have to run the following command.

bit export
Enter fullscreen mode Exit fullscreen mode

This will deploy your new component library.

For an existing workspace when you want to edit your components or create new components, first you will need to import all deployed components by running.

bit import
Enter fullscreen mode Exit fullscreen mode

And after making all changes, use the same process as we did while deploying components.

Step 9: Install and use your deployed components on your react project.

In your react project, install your components and start using them.

the first time you are installing your components in your project, you will need to configure your bit organization or username first by running

npm config set '@your-username:registry' https://node-registry.bit.cloud
Enter fullscreen mode Exit fullscreen mode

After the configuration you won't need to do that again in your projects.

Then run

npm i @your-username/components.login
Enter fullscreen mode Exit fullscreen mode

Then you can start using your components as you used them in the composition files in your bit components.

That's it.

Creating and deploying React components with Bit.dev is a powerful way to streamline your development workflow and make your components reusable across different projects. By following the steps outlined in this article, you can easily create, test, and share React components with other developers using the Bit.dev platform.

Feel free to contact me if any questions.

Top comments (2)

Collapse
 
covernal profile image
covernal

Your detailed walkthrough on creating and deploying React components with Bit.dev is incredibly helpful. The step-by-step instructions, along with the clear explanations, make it easy for readers to follow along. Overall, a fantastic guide for developers looking to enhance their component-based development workflow with Bit.dev!
Keep up the excellent work!

Collapse
 
mike0120 profile image
Mike Lu

thanks