50

Build a Reusable Timer Component With React and Bit

 5 years ago
source link: https://www.tuicool.com/articles/hit/363emee
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Build a Reusable Timer Component With React and Bit

J7fQFbq.png!webNvQvqqU.png!web

So, we are going to develop our own countdown timer React component and use Bit to easily make it available for my whole team to use in their apps.

When done, you will have your own components like this:

More than that, you will learn how to easily share components from your different into a shared collection, and use them anywhere to build faster.

Introduction

Nodejs and NPM revolutionalized the JavaScript universe, which saw the rise of so many frameworks and tools: Angular, Lerna, React, etc. Some are extinct, some on the brink of extinction, some still flourishing.

Most JS frameworks still used today like Angular, React and Vue brought the use of components to build our UI. Every single view is componentized so we can aggregate all the components to form a complex and well-defined UI.

Components give us the ability to isolate view and logic and also to make our views reusable. It is said that if you find yourself copying-and-pasting your code it is obvious you have violated the DRY principle.

But with all the goodies the components bring to the table, we still have the problem of sharing the components across multiple projects. NPM is here for a while but you find yourself creating repos for every component you won’t share them at all. Lerna and Yarn came with their own brilliant solution but still the same story as sharing components is just not good enough.

In came Bit,

Bit turns your components into building blocks you can instantly isolate and publish from any project.

All your components will be organized and made available for your team, which easily can discover, install and even develop components in any project. — Jonathan Saring

Bit is an awesome tool that helps you seamlessly share your components across your projects.

For example, we have this React app:

react-app/
 - src/
 - components/
  - login/
   - login.component.js
   - login.component.css
  - register/
   - register.component.js
   - register.component.css
 - App.js
 - index.js

See in the above project, we have a components folder that holds the login component; which will display and hold the logic for signing in into our app. The register component holds the logic and view of our registration.

Now, in each new project we start, we will find that will need to build login and register components for the projects. It will be cumbersome and boring and repetitive to build register and login components afresh for each project. Can’t we make a generic component and share it among the projects?

We might use NPM but it will require us to seperate the components into repos and push them to NPM. It solves the issue but it’s quite hectic creating repos and pushing and pulling. Lerna can help us do the same in one repo, but won’t solve most of the over-head generating issues around it.

With Bit, we simply move into the project and isolate the components without creating new repo or folders or projects and push to Bit registry . Since automatically isolates the components and handles all their dependencies, configurations and versioning, we can publish 500 components in minutes without changing a single code-line.

Now, when working on another project and we need the login or the register component we simply add the component bit import login.component or bit import register.component . That's all, the components are ready for you at your disposal, no extras node_module or entry into package.json.

If you prefer, you can even install them using the NPM/Yarn clients.

Now, in this post lets demo how to build a Timer component and how to share it among projects using Bit.

A countdown timer is used to display the countdown to any event. Like, in the wedding anniversary, countdown timers can be used to cut the cake. You know the popular: “10! 9! 8! …0!”

Installing Bit and Scaffolding React project

The first thing we need to install the Bit CLI tool globally so that we can use from anywhere in our system.

$ npm i bit-bin -g

Now we create our React project but before we do that make sure you have create-react-app installed:

$ npm i create-react-app -g

Lets scaffold the React project:

$ create-react-app react-app

Next, we initialize bit in the directory:

$ bit init
ymY7rqm.png!web

Building the Timer component

Now, let’s create the Timer component.

First, create a components folder. With this, we are trying to aggregate the structure of our project to match according to their functionality. So the components/ folder will hold all of our components

$ mkdir src/components && mkdir src/components/timer
$ touch src/components/timer/timer.component.js
$ touch src/components/timer/timer.component.css

The touch src/components/timer/timer.component.js will hold the view and logic, touch src/components/timer/timer.component.css will hold the styling.

Open touch src/components/timer/timer.component.js and paste the following code:

QrEfimB.jpg!web

Starting at the constructor , we bound the count function to the class instance, we declared our state object which contains days , minutes , hours , seconds , and time_up properties. They will store the current values when our timer ticks(.i.e. counts down). We defined the this.x variable which will hold a reference to setInterval function, this.deadline will store the time or the deadline, our timer will tick down to.

We used componentDidMount to start our timer. You know, the constructor first executes, followed by componentDidMount and finally, the render method comes last. That's the reason we delegated initialization to the constructor then, started the timer at componentDidMount , render then displays the values: hours , days , minutes , seconds .

constructor ==> componentDidMount ==> render

Finally, we exported our CountDown class so that our users can import the CountDown component in their React project when they install our library.

Now, we are done with our component, the next step is to style the component.

Open the src/components/timer/timer.component.css and paste the following:

QrEfimB.jpg!web

Open App.js and render the Timer component:

import React, { Component } from 'react';
import './App.css';
import TimerComponent from './components/timer/countdown'
class App extends Component {
    render() {
        return ( 
            <>
                <TimerComponent />
            </>
        );
    }
}
export default App;

Run npm run start on your terminal and navigate to localhost:3000 , you will see our Timer component rendered.

7FFbEjA.png!web777RbyV.png!web

Building Components

We need to build our components, to do that we need to add compilers which will render the components in the Bit web UI. The compilers render the components in a remote environment, the components being React components needs transpilers to compile the components to renderable version. This only needs to be defined once per project, no matter how many components we publish.

$ bit import bit.envs/compilers/react --compiler
username: chidume
password:
the following component environments were installed
- bit.envs/compilers/[email protected]
FFjURb7.png!webFvyUr2Q.png!web

Tracking Components

We need to tell bit which files it has to create Bit registries for. We use the bit add command to achieve that.

The command stages the files in the Bit workspace which tells Bit to model the files as components. In our project, we will stage the login and register components.

$ bit add src/components/*
AJfiAjV.png!webNZ7jeme.png!web

In this case, we used the glob pattern to tell Bit to track all the files in the components folder. You can also use specific paths if needed.

Now we need to isolate and tag the tracked components with a version. This locks each component dependency graph in an immutable state embrace.

$ bit tag --all 0.0.1
Q7BrI3q.png!web

Creating Collection and Sharing Components

Now, we need to create a collection in bit.dev . The collection works like a space where components of the same nature or functionality are shared.

So head over to bit.dev and create a collection .

ea22Iva.png!webFfUnqe7.png!web

So now the collection is ready, but it’s still empty.

ymEFziU.png!webaYBRfev.png!web
nEjqy2J.png!webi2uuam6.png!web

Now, we have a collection and you can push the staged components to the collection:

$ bit export <YOUR_ACCOUNT_NAME_HERE>.<YOUR_COLLECTION_NAME>
F32q2i7.png!web

Now, you can go to bit.dev and move to your account and collection to see your components; browse through them, view them rendered and use them in other projects. Here’s the component we just shared!

yANZzij.png!webRJfUFjQ.png!web

In the component page itself we can play with the component online, and when ready we can just install or import it into any other project.

Using the Timer component from Bit in another project

Create another React project:

$ create-react-app react-bit

The folder looks like this:

7jQVrye.png!webMJZvQnR.png!web

This project is different from the react-app project we created earlier that has the timer component. Now, let’s say we need the timer component in this project, we first initialize a Bit workspace via bit init and simply import the timer component from Bit like this:

$ bit init
$ bit import <YOUR_ACCOUNT_NAME_HERE>.<YOUR_COLLECTION_NAME>/timer --path src/components/timer

This command will install the timer from the Bit registry into src/components/timer folder of react-bit

raqyUzQ.png!webIvyEbmR.png!web

You see, we can now render the timer component anywhere we want. I need it in the App.js file

import React, { Component } from 'react';
import './App.css';
import TimerComponent from '@bit/chidume.my_components_92.timer/timer'
class App extends Component {
    render() {
        return ( 
            <>
                <TimerComponent />
            </>
        );
    }
}
export default App;

We did import TimerComponent from '@bit/<YOUR_ACCOUNT_NAME_HERE>.<YOUR_COLLECTION_NAME>/components/timer' instead of import TimerComponent from './components/timer' Why?

When you import a component with Bit, it creates links in the project’s node_modules dir.

3IZFzuR.png!webE3mIRvq.png!web

This means that you can (and should) import these components using an absolute path.

You see how easy it is to use Bit. If it was NPM we would need to deal with installing the module into node_modules and dependencies.

We can also make changes to the timer component here although it wasn’t its original birthplace we can make changes to the timer component and sync it with the version in Bit. That’s the beauty and uniqueness of Bit, you can merge changes in components from different projects !

Conclusion

We are in the age of coding using components. Bit brought us the ease with which we can reuse our components in different projects without the overhead and limitations we had before. It also makes our building projects very fast because we can easily pull in any components we want without re-writing the components or installing entire libraries.

Remember, if you find yourself copy-and-pasting code, you are violating the DRY (Don’t-Repeat-Yourself) principle, so it’s about is time to share code.

If you have any question regarding this or anything I should add, correct or remove, feel free to comment below and ask anything. Thanks !!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK