HDTuto.com

React JS Custom Component Example



Now, let's see tutorial of how to create custom component in react js. if you have question about create component in react js then i will give simple example with solution. This post will give you simple example of generate component react . This article goes in detailed on create new component in react .

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 - HDTuto.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...




May 31, 2020 | Category : React



Blog Search


Copyright © 2020 HDTuto.com. All rights reserved.