How to create Component in React

functional component#

creating component in react is as simple as creating normal function. actually react components are nothing but the javascript functions.

for example below component.

export default function Greetings(){
    return (
        <h2>This is greeting</h2>
    )
}

passing props to component is like we are defining attributes to html element

for example:

<Greetings text="John" />

and that props will be accessible using props.text or we can do destructing like {text} in component function parameter .

for example

export default function Greetings(props){
    var text = props.text
    ...
}

or simply

export default function Greetings({text}){
    var text = text
}

we will go deep into react hooks in further post.

In return statement of component there must be only one parent element, we cannot return more than one elements like below.

export default function Greetings({ text }){
    return (
        <div></div>
        <div></div> // this is not valid 
    )
}

instead we can wrap multiple elements into one parent div elements or we can use Fragments or <> </> if dont want that extra div

like below

export default function Greetings(props) {
    return (
        <div> {/*  can use <> or <Fragments> */}
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            ..... /// and so on
        </div> {/* </> or </Fragments> */}
    )
}

class based component#

for creating component in class based react which before introduction of hooks, we are creating class and extending that class with React.Component class

look at the example below

class ButtonComponent extends React.Component {

    render(){
        return (
            <div>
                <button onClick={this.props.onClick}>{this.props.name}</button>
            </div>
        )
    }
}

there is render() method in class based component which is executed and renders view

for using component is same like we did for functional component

<ButtonComponent onClick={()=>console.log("btn clicked")} name="Log In" />
comments powered by Disqus