What are components in javascript?


Components are like functions that return HTML elements.


React Components

Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML.

Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.

In older React code bases, you may find Class components primarily used. It is now suggested to use Function components along with Hooks, which were added in React 16.8. There is an optional section on Class components for your reference.


Create Your First Component

When creating a React component, the component's name MUST start with an upper case letter.

Class Component

A class component must include the extends React.Component statement. This statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.

The component also requires a render() method, this method returns HTML.

Example

Create a Class component called Car

class Car extends React.Component {
  render() {
    return 

Hi, I am a Car!

; } }

Function Component

Here is the same example as above, but created using a Function component instead.

A Function component also returns HTML, and behaves much the same way as a Class component, but Function components can be written using much less code, are easier to understand, and will be preferred in this tutorial.

Example

Create a Function component called Car

function Car() {
  return 

Hi, I am a Car!

; }



Rendering a Component

Now your React application has a component called Car, which returns an

element.

To use this component in your application, use similar syntax as normal HTML:

Example

Display the Car component in the "root" element:

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();

Run Example »


Props

Components can be passed as props, which stands for properties.

Props are like function arguments, and you send them into the component as attributes.

You will learn more about props in the next chapter.

Example

Use an attribute to pass a color to the Car component, and use it in the render() function:

function Car(props) {
  return 

I am a {props.color} Car!

; } const root = ReactDOM.createRoot(document.getElementById('root')); root.render();

Run Example »


Components in Components

We can refer to components inside other components:

Example

Use the Car component inside the Garage component:

function Car() {
  return 

I am a Car!

; } function Garage() { return ( <>

Who lives in my Garage?

); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render();

Run Example »


Components in Files

React is all about re-using code, and it is recommended to split your components into separate files.

To do that, create a new file with a .js file extension and put the code inside it:

Note that the filename must start with an uppercase character.

Example

This is the new file, we named it "Car.js":

function Car() {
  return 

Hi, I am a Car!

; } export default Car;

To be able to use the Car component, you have to import the file in your application.

Example

Now we import the "Car.js" file in the application, and we can use the Car component as if it was created here.

import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './Car.js';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render();

Run Example »


Test Yourself With Exercises

Exercise:

Name the following React component "person".

function (props) {
  return 

Hi, I'm {props.name}

; }

Start the Exercise



What are components in javascript?

Photo by Kaboompics from Pexels https://www.pexels.com/photo/geometric-decoration-5836/

Recently, I struggled to create an app with vanilla javascript following the component methodology. That is —

  1. One component should focus on one section of the UI.
  2. One component shouldn’t access another’s html directly.
  3. The component encapsulates its html, css and javascript.
  4. Each component has some way to interact with others.

This approach has many advantages. It aligns with Single Responsibility Principle, so we have good separation of concerns, which in turn makes debugging easier.

Due to these advantages every major framework or library like React, Vue, Angular uses this.

If we consider React it follows all these rules —

  1. We make class components which are specific to one section of UI.
  2. Direct access to DOM is forbidden.
  3. Each component has a render method which is reponsible for the html of component. No component directly changes another’s html.
  4. We use Redux so that when state of one component changes, then other parts of the app aka components can be updated.

So how do we do all this in vanilla javascript ?

The first three consideration are design related and very easy with es2017. Today I want to focus on the fourth requirement. How do we make the components interact with each other.

For example, let’s assume we have a Search component and a List component. Their use is self explanatory, the List component shows a list of items and we can filter the items using the Search component.

The filter feature needs us to pass the search term from the Search component to the List component so that the List component shows only those items which matches the search term.

So one way of doing this is that we expose some methods of List component likeupdateList and call this function from the Search component whenever the user inputs something. But this has a serious problem. We have tightly coupled both the components. If say we make some changes in the updateList method then it may break the search functionality. Thus the responsibility has been divided among the two. And this is a problem. One more thing is that for now we are just talking about two components. Our app will probably have much more components than these and if all our depending on one another debugging the code will become a nightmare. How can we avoid this ?

We can use the pub/sub design pattern to make the components talk in a decoupled fashion. This uses the concepts of events.

One or more components subscribe to an event, so that when a certain event occur from anywhere in the app, a callback is triggered through which the component can handle updates.

The event occurs when one component publishes it. It’s important that the published event is unique to that component. That is only one component can publish a certain event and nobody else.

In our example, we can do this —

  1. The Search component publishes an event say searchComp/search whenever the user submits a search term.
  2. The List component subscribes to this event. So every time the user submits a search term, the List component gets to know about this and so it can update the list.

Let’s see some code to understand how we actually do this.

Note — I’m using es2017 with import statements and object destructuring.

// searchComponent.js
import { publishEvent } from './utilities/eventBus';
const searchInputElem = document.getElementById('searchInput');
const searchSubmitElem = document.getElementById('searchSubmit');
searchSubmitElem.addEventListener('click', function () { publishEvent('searchComp/search', {
query: searchInputElem.value
})
})--------------------------------------------------------------------// listComponent.jsimport { subscribeEvent } from './utilities/eventBus';subscribeEvent('searchComp/search', function ({ query }) {
console.log(`you entered ${query}`);
//do something else
})

Merits of this approach —

  1. In the future if new features are added we just have to publish new events and add subscribers to it.
  2. The event publisher doesn’t have to know anything about the components which have subscribed to it.

Implementing the Event Bus

As you can see the previous code snippet, the eventBus utility provides two methods subscribeEvent and publishEvent to handle the events.

Let’s see how this utility is implemented —

// utilities/eventBusconst events = {};export function subscribeEvent(event, listener) {
if (!events[event]) {
events[event] = [];
}
if (!events[event].includes(listener)) {
events[event].push(listener);
}
}
export function publishEvent(event, payload = {}) {
const listeners = events[event];
if (!listeners) {
return;
}
for (let i = 0, l = listeners.length; i < l; i += 1) {
listeners[i](payload);
}
}

Explanation —

  1. events is an object whose keys represent an event.
  2. Each key has an array of listeners as it’s value.
  3. When an event occurs, the corresponding key from the events object is selected and then all the listeners are called.

Where to go from here —

  1. You can add an unsubscribeEvent method so that component can stop listening to an event.
  2. You can make preloader component which subscribes to serverAction/start and serverAction/finish event and shows/hides accordingly.
  3. Check out Code Runner, to see a complete project using this pattern.

What is component and element in JavaScript?

A React Element is what gets returned from components. It's an object that virtually describes the DOM nodes that a component represents. With a function component, this element is the object that the function returns. With a class component, the element is the object that the component's render function returns.

What is component and its types?

Components usually come in two types, functional components and class components, but today we will also be talking about pure components and higher-order components.

How do you write components in JavaScript?

Implement a Custom Component in JavaScript.
Step 1: Create Your Constructor..
Step 2: Add the Component ID..
Step 3: Initialize the Component..
Step 4: Add a Function to Trigger a Query When the Enter Key is Pressed..
Step 5: Add a Search-As-You-Type Option..
Step 6: Add the Newly Created Component in a Search Page..

What are components and props?

Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.