React Component's

React Component's

Before knowing about what’s the component is we have to know about the React.js. So, React is a JavaScript library which is used to build UI (User Interface). UI is built using small units like button, text, images and colors. React help’s to combine these all in a reusable and nestable components.

React application’s are built using the isolated piece of UI called Components.

A React component is a JavaScript function which is built using HTML element OR markup. It can be Button or a Card or an entire page.

Example of a component :-

import React from 'react';

const MyComponent = () => {
  return (
    <div>
      <h1>Hello, World!</h1>
      <p>This is a simple React component.</p>
    </div>
  );
}

export default MyComponent;

Usage of above component in Parent Component:-

import React from 'react';
import MyComponent from './MyComponent'; // make sure to adjust the path as needed

function App() {
  return (
    <div>
      <MyComponent />
    </div>
  );
}

export default App;

Component returns an <div> tag with <h1> and <p> tag. <div> is written like HTML, but it is actually JavaScript under the hood! This syntax is called JSX, and it lets you embed markup inside JavaScript.

Naming Convention for Component : -

It is always a good practice to write your component name in Pascal Case (Example:- FirstName)

Exporting and importing a component : -

We can create multiple component in a single file there is no any problem in this. But, think about the code readability and number of lines of code in a file. So for the code readability purpose component can be created in another file or folder and can be be used wherever required. We can export the component where it is created and import wherever we need that component

How to export the component

There are two ways to export the component

  1. Default export

  2. Named export

Example of default export: -

// myModule.js
const myFunction = () => {
    console.log("This is a default exported function");
};

export default myFunction;

Example of named export: -

// utils.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

Importing a component: -

To use the component in any other file we need to first import the component. Like export, import has also two types named and default.

// default import
import MyComponent from './mycomponent'

//named import
import { Add, Subtract } from './mycomponent';