DEV Community

SavvyShivam
SavvyShivam

Posted on

Components in ReactJS

Components

A React component is a part of the UI you create. It is a reusable and modular piece of the UI that has its view and other logic separated out into either a function or class.

There are 2 types of components in React

  • Functional Component (Preferred)

  • Class Based Component

They work on the same principles although functional components have better syntax and thus are preferred.

They are one of the core concepts of React. In other words, we can say that every application you develop in React will be made up of pieces called components. Components make the task of building UIs much easier. You can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI.

A Functional React component is a JavaScript function that will return a markup.
A React component is a JavaScript function that you can easily use markup with.

The following code shows a component named Button in the index.js file:

We have defined a Component called Button. Note that the name of the component starts with a capital letter.
Secondly, we have defined a function called clickHandler with which we will be able to log “Clicked” in the console by using the onClick event handler.
Lastly, we return the button tag and with the onClick attribute being equal to the clickHandler function

Rendering the Button component:

We render the Button component in the ReactDOM by using a self-closing tag
button component

The component’s name in React always starts with a capital letter. This is done to distinguish them from the HTML attributes
In the above piece of code, we can see that a function named App has been defined in the component. The name of the function must also start with a capital letter
The div element is given a class name(camelCase) App and there is a h1 tag that contains the string “This is your First Component”
This is how we add a markup to the React Components
Lastly, we export this function as default.

There are two primary ways to export values with JavaScript: default exports and named exports.

  • Default Export

  • Named Export

Default Export

The above-mentioned code is an example of Default Export. A file can have only one default export.

Named Export :

Unlike Default Export, we do not use the term “default” while exporting the function. There can be multiple named exports in one file.
The following is an example of named exports.

The below code shows how to import the above-mentioned exported functions:

Note: While using a default export you can use any name to import it. It doesn’t necessarily have to be the same name as that of the function.
Default named

Top comments (0)