React JS

React Language Constructs

React Language Constructs

React Language Constructs

Conditional Construct : if - else Statement

import React from "react";
import Electronics from "./Electronics"
import Book from "./Book"

class HomeComponent extends React.Component {
    render() {
        const itemToShow = this.props.itemType;

// if else based on props value, passed from parent
        if (itemToShow == 'Books') {
            return <Book />;
        } else {
            return <Electronics size="42" year="2010" bestModel="Sony" favModel="HP"></Electronics>;
        }
    }
}
export default HomeComponent;


//========== parent component with props
import HomeComponent from './HomeComponent';
const MasterComponent = ({ children }) => {
    return (<>
        <HomeComponent itemType="Electronics"></HomeComponent>
    </>
    )
}

export default MasterComponent



Logical Construct : &&, || Operator

import React from "react";
import Electronics from "./Electronics"
import Book from "./Book"

class HomeComponent extends React.Component {
    render() {
        const itemToShow = this.props.itemType;
        const userrole="admin";

        if(userrole.indexOf("admin") > -1 || userrole.indexOf("superadmin") > -1){
            if (itemToShow!=null && itemToShow == 'Books') {
                return <Book />;
            } else {
                return <Electronics size="42" year="2010" bestModel="Sony" favModel="HP"></Electronics>;
            }
        }
    }
}
export default HomeComponent;



Ternary Operator

import React from "react";
import Electronics from "./Electronics"
import Book from "./Book"

class HomeComponent extends React.Component {
    render() {
        const itemToShow = this.props.itemType;  
        return (
            <>
                {itemToShow == 'Books' ? <Book /> : <Electronics size="42" year="2010" bestModel="Sony" favModel="HP"></Electronics>}
            </>
        );
    }
}
export default HomeComponent;






Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram