ReactJS - How to create ReactJS components

June 27, 2020

Introduction

In this post, we will talk about basic of how to create components in ReactJS. Whatever is rendered through ReactJS is one or more component. Component os the backbones of ReactJS.

There are two ways to create components in ReactJS:

1. Via Function

The simplest way to create a component is via using a function.

import React from 'react'

export default function App() {
    return (
        <div>
            <h1>Hi there</h1>
        </div>
    )
}

Passing Props

To pass props to a functional component, use:

import React, {Component} from 'react';

function Test(prop) {
    return (
        <div>
            <h1>Hi {prop.name}</h1>
        </div>
    )
}

function Test2({desig, name}) {
    return (
        <div>
            <h1>Hi {desig}, {name}</h1>
        </div>
    )
}

function Test3(obj) {
    return (
        <div>
            <h1>Hi {obj.data.desig}, {obj.data.name}</h1>
        </div>
    )
}

class App extends Component {
    render() {
        const data = {id: 1, name: 'Rahul', desig: 'Admin'};
        return <React.Fragment>
            <Test name="Rahul"/>
            <Test2 name="Rahul" desig="Engineer"/>
            <Test3 data={data} />
        </React.Fragment>
    }
}

export default App;

Output:

Hi Rahul
Hi Engineer, Rahul
Hi Admin, Rahul

In above example, I have shown three examples on how you can pass the properties or data or props to the functional component.

2. Via Class

Another way to create component is to have a class inherited through React’s Component class.

import React, { Component } from 'react'

export default class App extends Component {
    render() {
        return (
            <div>
              <H1>Hi</H1>               
            </div>
        )
    }
}

Passing Props

import React, {Component} from 'react';

class Test1 extends Component {
    render() {
        return (
            <div>
                <h1>Hi {this.props.name}</h1>     
            </div>
        )
    }
}
class Test2 extends Component {
    render() {
        return (
            <div>
                <h1>Hi {this.props.person.name} {this.props.person.id}</h1>
            </div>
        )
    }
}

class App extends Component {
    render() {
        const data = {id: 1, name: 'Rahul', desig: 'Admin'};
        return <React.Fragment>
            <Test1 name="Rahul"/>
            <Test2 person={data}/>
        </React.Fragment>
    }
}
export default App;

Output:

Hi Rahul
Hi Rahul 1

Its totally your choice as to how to create components. Traditional javascript developers loves function components. As OOPs programmer loves class components. Although class provides lot of other functionalities like states, lifecycle events etc. Newer version or ReactJS also provides a way to hook states into functional components.


Similar Posts

Latest Posts