How to create components in ReactJS

  356 views   7 months ago React

In this article, we will share with you how to create components in React Js. we all know that components are a very basic and small part of code in react js. it's write in different files and import the main file.

Why Create a Components in ReactJs?

First, things are what are components in react js? the component is a small pease of file code which we can use or import in our main application index.js file.

And, the second question is comes to our mind why create components in react js? so, it's the simple answer is to manage the large application's code in easy ways. we can also write all code in index.js file without creating any components in react js. but it is so difficult to understand when the application becomes large.

Create a New React App

Run the following command in your terminal to create a new fresh React.js application.

sudo npx create-react-app helloworldapp --use-npm

After done or create React.js application in your local system. application structure looks like bellow.

helloworldapp
├── build
├── node_modules
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── serviceWorker.js
├── .gitignore
├── package.json
└── README.md

Create a Demo Component

After, create the fresh reactJs application then now we need to create one test component for an example. create the src/DemoComponent.js file and write the following code into this component file.

import React from 'react';

const DemoComponent = () => {
	return (
		<div>Hi, i am a component!</div>
	);
};

export default DemoComponent;

Import Component

Now, open your src/index.js file and just copy past the following code into it.

// import the react and the reactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';
import DemoComponent from './DemoComponent';

// Create react component
const App = () => {
	return (
		<div>
			Hello World,
			<DemoComponent />
		</div>
	);
};

// Take the react component and show it on the screen
ReactDOM.render(
	<App />,
	document.querySelector('#root')
);

After done changes then how to run it? just run the following command in the terminal.

sudo npm start

Output :

the output will be print in a web browser looks like

Hello World, 
Hi, i am a component!

We, hope it can help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]