What are React Components?

Subscribe to my newsletter and never miss my upcoming articles

Third post of this series. In this tutorial we will learn what are Components and how to make function components.


What are Components?

Components are the building blocks of all sites and apps created using React.

How components are used to create sites and apps in React.

They serve the same purpose as JavaScript functions, but work in isolation and return HTML via a render() function.

By organizing our sites and apps into components, we are able to work with our UI as separate parts.

React makes creating components as easy as creating JavaScript functions.

By having many components, we can piece together components to make any number of site pages.

How to create Components in React?

Creating components in react is as easy as creating functions in JavaScript. If you remember the example in our last post , we have already created a component. App.js.

Let's make a new component
Before we start, you must know that there are two types of components - Class based components and Function components.

Earlier only Class components could manage states (Next post regarding this), but after the addition of hooks in React v16.8.0 we can manage states in Function components as well. In this tutorial we will learn how to make function components because it is the easy, intuitive and modern way to create components in react. Just know that there is an other way too.

Don't worry if you didn't understand terms like state and hooks - they will be covered later.

  • To create a new component, create a new JS file in the src folder and give it whatever name you like (e.g. Cool.js) Remember that a component name must start with and upper case character.
  • Now inside this file create function with the same name as the component. Don't forget to import react at beginning and export the function at the end. Your code should look something like this.
import React from 'react'; 
let Cool = () => {
  return (
    <p>This is reusable component</p>
   ); 
}
export default Cool;

Now, simply use the import statement to import this file and you can use anywhere- either in the index.js or in any other component. Lets use this in our root file that is index.js .

Your index file should look something like this.. (without the comments or those forward slashes)

import React from 'react'; // Compulsory to import react and react dom
import ReactDOM from 'react-dom'; 
import App from './App'; 
import Cool from './Cool'; 
ReactDOM.render(        // Render method to render components on DOM
  <React.StrictMode>  // Enables strict mode in React
    <App />    // Using the App and Message components
    <Message />
   </React.StrictMode>
   document.getElementById('root') // Container to render all the React Elements in HTML
);

Got to the project directory in the terminal and run npm start to see you components in action.


⚡Thanks For Reading | Happy Reacting😂

No Comments Yet