React JS Tutorial - Components

In this tutorial, we will learn about components, which are the building blocks of any React app. A typical React app will have many components, and understanding how to create and use them is essential.

Simply put, a component is a JavaScript class or function that optionally accepts inputs, known as properties (props), and returns a React element that describes how a section of the User Interface (UI) should appear.

Creating a Component

Let's create a component inside our React project. First, go to the project directory and create a new folder inside the src directory. Let's call this folder "components".

Inside the components folder, create a new component file called "Post.js". Open this file and create a class component.

First, import React and the Component class, and then create a class as follows:


import React, { Component } from 'react'

class Post extends Component {
render() {
return (
<div>
<h1>This is Post Component.</h1>
</div>
)
}
}

export default Post;

Next, import this component into the "App.js" file as follows:


import Post from './components/Post';

Now, remove the <header/> element and add the <Post /> component in its place. Save the file and let's check the output.

Go to your browser and you should see the Post component rendered. You can also render JavaScript code inside the component by wrapping it in curly brackets.

Let's try this by printing the current date and time. Go back to the Post component and add the following code:


{new Date().toLocaleString()} 

Now, let's see the output in the browser. You should see the current date and time displayed.

That's it! You have successfully created a component in React. By following these steps, you can create reusable components to build your React app.