How to Create Custom Component in React?

By Hardik Savani September 6, 2020 Category : React JS

Hi All,

This article is focused on react custom component example. i would like to show you how to make custom component in react native. step by step explain how to create custom component in react js. This post will give you simple example of create component in react js.

In this tutorial, i will show you two way to create custom components in react js. you can simply create component class and use it in your react app.

I am not going to confuse you more, so, let's see both very simple example of creating react nativ custom component.

Example 1:

src/index.js

import React from 'react';

import ReactDOM from 'react-dom';

import * as serviceWorker from './serviceWorker';

const MyCustomComponent = () => {

return <div>

<h1>Hello World!</h1>

<p>This is Custom React Component Example.</p>

</div>

}

ReactDOM.render(

<React.StrictMode>

<MyCustomComponent />

</React.StrictMode>,

document.getElementById('root')

);

serviceWorker.unregister();

Now you can run react app and you will find out layout as like bellow:

Example 2:

In this example, we will create MyCustomComponent component with separate file and use it with index.js file.

src/MyCustomComponent.js

import React from 'react';

function MyCustomComponent() {

return (

<div className="container">

<h1>Custom Component in React Example - ItSolutionStuff.com</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

</div>

);

}

export default MyCustomComponent;

src/index.js

import React from 'react';

import ReactDOM from 'react-dom';

import MyCustomComponent from './MyCustomComponent';

import * as serviceWorker from './serviceWorker';

ReactDOM.render(

<React.StrictMode>

<MyCustomComponent />

</React.StrictMode>,

document.getElementById('root')

);

serviceWorker.unregister();

Now you can run react app and you will find out layout as like bellow:

I hope it can help you...

Tags :
Shares