Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

React-js Fundamental, Installation of React Js, What is React JS, Flow of React JS


What is React JS:

ReactJS is a declarative, efficient, and flexible

JavaScript library for building reusable UI components. 

It is an open-source, component-based front-end library responsible only for the view layer of the application.

 It was created by Jordan Walke, who was a software engineer at Facebook. 

It was initially developed and maintained by Facebook and was later used in its products like WhatsApp & Instagram. 

Facebook developed ReactJS in 2011 in its newsfeed section, but it was released to the public in the month of May 2013.

Today, most of websites are built using MVC (model view controller) architecture.

 In MVC architecture, React is the 'V' which stands for view, whereas the architecture is provided by the Redux or Flux.



⚙️ Key Features of React.js:

  1. Component-Based Architecture

    • Everything in React is built using components — small, reusable pieces of code that define how a part of the UI looks and behaves.

  2. Virtual DOM (Fast Rendering)

    • React uses a virtual representation of the DOM to quickly detect what changed and update only that part of the page — making it very fast.

  3. Declarative Syntax

    • You describe what you want to show, not how to do it. React handles the UI updates automatically.

  4. JSX (JavaScript XML)

    • React uses JSX — a syntax extension that lets you write HTML inside JavaScript easily.
      Example:

      const element = <h1>Hello, World!</h1>;
  5. Unidirectional Data Flow

    • Data flows in one direction (from parent to child), making it easy to understand and debug your app.

  6. Reusable Components

    • Once a component is built, you can reuse it anywhere in your app — saving time and keeping code clean.

  7. Strong Community & Ecosystem

    • Huge support from developers worldwide, along with libraries like React Router, Redux, and Next.js.


💻 Example: Simple React Component

import React from 'react'; function Welcome() { return <h1>Hello, React!</h1>; } export default Welcome;

🌐 Common Use Cases:

  • Building Single Page Applications (SPAs)

  • Creating Dynamic Dashboards

  • Developing E-commerce and Social Media Apps

  • Powering mobile apps using React Native


🚀 Why Use React.js?

  • Faster performance than traditional JavaScript or jQuery

  • Easy to maintain and scale large apps

  • Popular in modern web development and high-demand in the job market

💡 Definition of Component in React.js:

A component in React is a reusable, independent piece of UI that defines how a part of the web page should look and behave.
Each component is like a building block — you combine many components to build a complete web application.


🧠 Simple Explanation:

A component is just a function or class in React that returns HTML (JSX) to display on the screen.

Think of it like LEGO blocks —
each block (component) can be used multiple times to build a large structure (the app).


🧩 Types of Components in React:

  1. Functional Components (Modern way)
    These are simple JavaScript functions that return JSX.

    function Welcome() { return <h1>Hello, React!</h1>; }
  2. Class Components (Older way)
    These use ES6 classes and have additional features like lifecycle methods.

    import React, { Component } from 'react'; class Welcome extends Component { render() { return <h1>Hello, React!</h1>; } }

⚙️ Key Features of Components:

  • Reusable — You can use the same component multiple times.

  • Independent — Each handles its own structure and logic.

  • Composable — You can combine multiple components to make complex UIs.

  • Maintainable — Easier to manage large applications.


🧱 Example: Multiple Components Together

function Header() { return <h1>My Website</h1>; } function Footer() { return <p>© 2025 My Website</p>; } function App() { return ( <div> <Header /> <p>Welcome to my website!</p> <Footer /> </div> ); } export default App;

Here, App is the main component, and Header and Footer are child components.


📘 In One Line Definition:

A component in React is a reusable piece of code (function or class) that defines how a specific part of the user interface should look and work.

 The components are the heart of all React applications. These components can be nested with other components to allow complex applications to be built of simple building blocks.

 Here’s a step-by-step guide on how to install React.js and create your first React project 👇


🧩 1. Prerequisites

Before installing React, make sure you have these installed on your system:

Required Tools

ToolDescriptionHow to Check
Node.jsJavaScript runtime used to run React toolsnode -v
npm (Node Package Manager)Comes with Node.jsnpm -v

👉 If not installed, download from:
🔗 https://nodejs.org


⚙️ 2. Create a New React Project

You have two easy ways to set up React:


🅰️ Method 1: Using Create React App (Recommended for beginners)

🪜 Steps:

  1. Open Command Prompt / Terminal

  2. Run this command:

    npx create-react-app my-react-app

    (Here my-react-app is your project name — you can change it.)

  3. Go into your project folder:

    cd my-react-app
  4. Start the development server:

    npm start
  5. 🎉 Open your browser and visit:

    http://localhost:3000

    You’ll see “React App” running successfully.


🅱️ Method 2: Using Vite (Faster alternative)

Vite is a modern build tool that’s faster and lighter than Create React App.

🪜 Steps:

  1. Run this command:

    npm create vite@latest my-react-app
  2. Choose:

    • Framework: React

    • Variant: JavaScript or TypeScript (choose JavaScript if new)

  3. Go to the project folder:

    cd my-react-app
  4. Install dependencies:

    npm install
  5. Start the app:

    npm run dev
  6. Open the link shown in the terminal (usually http://localhost:5173).


🧠 3. Folder Structure Overview

After installation, you’ll see files like:

my-react-app/ ┣ src/ ┃ ┣ App.js # Main React component ┃ ┣ index.js # Entry pointpublic/ ┣ package.json ┗ node_modules/

What you should learn before REACT-JS?

1)  JS, JSX, JS with ES6

2)  Object-oriented JavaScript or JSX 

What is MERN?

MERN  Means

M  --->  MONGO

E --->   Express JS

R ---->  REACT JS

N --->   NODE JS

What is MVC Architecture?

MVC is the design pattern to distribute the project on different project layers, M stands for Model which is used to create the data access layer, V stands for View which is used to contain the design layer and C stands for Controller is used to contain business code of an application. React Js is used to create the View Layer of an application.

Installation of React-JS?

1)  Install NODE JS in Machine

https://nodejs.org/en/download/

2)  npm install react   

if react is already present

npm view react version

3)  npx create-react-app app-name

4)  cd app-name

5)  npm start

node_modules:-    the base package of reacting that is used to contain all the libraries of a node JS.

public:-

it contains all assets of the project means js, CSS, and images files of an application will be implemented by the public folder.

src:-  it means source, all application components will be defined under src folder. start-up file of 

react application is index.js means when we call 

any application then the first index.js file will be 

called.

What is the flow of react js application:-

In react first index.html file will be loaded that will display the result of index.js and index.js file is the startup file that is used to call the app component of the application using app.js file.'

1) public ---> index.html (provide container to show APP Data)

2) result of a component)----> index.js(calling APP Data)

3) component) ----> app.js(component)  (Create Ressable code)

"we should never write any code on .html, all code"

(design, business logic) will be implemented by the component.




Example of React Life cycle with the mounting operation:-


Example using Functional Component:

import { useEffect, useState } from "react";

function MountingExample()
{
    const[a,setA] = useState(0)
     useEffect(()=>{
        console.log('mounting')
        return ()=>{
            console.log('unmounting')
        }
     },[]);

     useEffect(()=>{
        console.log('updating')
       
     });

     useEffect(()=>{
        console.log('updating')
       
     },[a]);
     function fun()
     {
        setA(a+1)
     }
      return(<div>
        <h1>React Life Cycle</h1>
        <button onClick={fun}>Click</button>
        {a}
      </div>)
}
export default MountingExample;

Example of Mounting in Functional Component:
import { useEffect, useState } from "react"

function FMounting()
{
    const[a,setA] = useState(1000)
    useEffect(()=>{
        setInterval(()=>{setA(20)},5000)

    },[])
    return(<div>
           <h1>Value is {a}</h1>
    </div>)
}

export default FMounting;

Example of Updating in Functional Component:
import { useEffect, useRef, useState } from "react"

function FUpdating()
{
    const [color,setColor] = useState("Red")
    const div1 = useRef(null)
    const div2 = useRef(null)
    useEffect(()=>{
        if(div1.current)
        {
            div1.current.innerHTML = color;
        }

    },[]);

    useEffect(()=>{
        if(div2.current)
        {
            div2.current.innerHTML = color;
        }

    },[color]);

    return(<div>
        <input type="button" value="ChangeColor" onClick={()=>setColor("green")} />
        <h1>{color}</h1>
        <div ref={div1}></div>
        <div ref={div2}></div>
    </div>)
}
export default FUpdating;


Example of Unmounting in Functional Component:

import React, { useEffect, useState } from "react"
function FUnmounting()
{
   const[show,setShow] = useState(true)
    let delHeader=()=>{
       setShow(false)
     }
    return(
   
     <div>
             {show && <Child />}
            <h1>Parent Component</h1> <br/>
            <input type="button" onClick={delHeader} value="HIDE HEADER" />
    </div>
    )
   
}

function Child()
{
    useEffect(()=>{
       
        return ()=>{
            alert("The component named Header is about to be unmounted.");
   
        }
     },[]);
   
       
   
       return(
        <div>
        <h2>HEADER Component</h2>
        </div>
       )
   
}
export default FUnmounting;

Mounting means putting HTML elements under the DOM.

import React from "react"
export class Example1 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {a: 1000};
    }
   
    componentDidMount() {
        setTimeout(() => {
          this.setState({a:20})
        }, 1000)
      }
    render() {
      return (
        <h1>{this.state.a}</h1>
      );
    }
  }
 
Updating:-

It means when we change the state of react ui then it will implement updating state.

import React from "react"
export class Example2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {favoritecolor: "red"};
      }
      shouldComponentUpdate() {
        return true;
      }
      changeColor = () => {
        this.setState({favoritecolor: "blue"});
      }
      render() {
        return (
          <div>
          <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          <button type="button" onClick={this.changeColor}>Change color</button>
          </div>
        );
      }
     
  }
Another Example of Updating:-
import React from "react";
export default class Example4 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {favoritecolor: "red"};
    }
    componentDidMount() {
      setTimeout(() => {
        this.setState({favoritecolor: "yellow"})
      }, 1000)
    }
    getSnapshotBeforeUpdate(prevProps, prevState) {
      document.getElementById("div1").innerHTML =
      "Before the update, the favorite was " + prevState.favoritecolor;
    }
    componentDidUpdate() {
      document.getElementById("div2").innerHTML =
      "The updated favorite is " + this.state.favoritecolor;
    }
    render() {
      return (
        <div>
          <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          <div id="div1"></div>
          <div id="div2"></div>
        </div>
      );
    }
  }


Unmounting:-

When component destroy the element from DOM objects then it is called unmounting.

import React from "react";
export default class Example3 extends React.Component {
    constructor(props) {
      super(props);
      this.state = {show: true};
    }
    delHeader = () => {
      this.setState({show: false});
    }
    render() {
      let myheader;
      if (this.state.show) {
        myheader = <Child />;
      };
      return (
        <div>
        {myheader}
        <button type="button" onClick={this.delHeader}>Delete Header</button>
        </div>
      );
    }
  }
 
  class Child extends React.Component {
    componentWillUnmount() {
      alert("The component named Header is about to be unmounted.");
    }
    render() {
      return (
        <h1>Hello World!</h1>
      );
    }
  }
 

What is a Component?

it is the business class or object of react js that is used to provide the design layer and code layer of an application.

react js is specially used to design single page applications and page components (header, sidebar, footer, content section) will be created by component.

type of component.

1)  Function Component:-

   function Functionname() {

       return ( 

            <div>

          </div>

           )

        }

    export default App;

    export means public accessibility to component

Function Component Example:-

function Addition()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a+b}</p>

       </div>

    );
}

export default Addition;

SI Component Example:-

function SI()
{
    var p=50000;
    var r=2.2;
    var t=2;
    return(
     <div>
       <p>Result is {(p*r*t)/100}</p>

     </div>

    );
}

export default SI;

How to call Multiple Components in React-JS:-

function Operation()
{
 
    return(
       
       <div>
      <Add />
      <Sub />
      <Multi />
      <Div />

       </div>

    );
}
function Add()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a+b}</p>

       </div>

    );
}
function Sub()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a-b}</p>

       </div>

    );
}
function Multi()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a*b}</p>

       </div>

    );
}
function Div()
{
    var a=10;
    var b=20;
    return(
       
       <div>
     
       <p>Result is {a/b}</p>

       </div>

    );
}
export default Operation;

Note:-  all exported components can be rendered by index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('root')
);

How to create program logic using components?

function Evenodd()
{
    const x = 11;
    var result;
    if(x%2==0)
      {
          result = "even"
      }
      else
      {
          result= "odd"
      }
    return(
       
       <div>
     
       <p>{result}</p>
       </div>

    );
}

export default Evenodd;

Example of SI Program:-

import { useState } from "react"

function SI()
{
    const[p,setP] = useState(0)
    const[r,setR] = useState(0)
    const[t,setT] = useState(0)
    const[res,setRes] = useState(0)
    function enterP(e)
    {
     setP(e.target.value)
    }
    function enterR(e)
    {
        setR(e.target.value)
    }
    function enterT(e)
    {
        setT(e.target.value)
    }
    function calc(e)
    {
        var si = (parseFloat(p)*parseFloat(r)*parseFloat(t))/100
        setRes(si)
        e.preventDefault()
    }
    return(<div>
     <form>
         <input type="text" onChange={enterP} placeholder="Enter P"  />
         <br/>
         <input type="text" onChange={enterR} placeholder="Enter R"  />
         <br/>
         <input type="text" onChange={enterT} placeholder="Enter T"  />
         <br/>
         <input type="submit" value="SI" onClick={calc} />
     </form>
      {res}

    </div>)
}
export default SI;

Example of Addition:-
import { useState } from "react";

function Hello()
{
   const[a,setA] = useState(0)
   const[b,setB] = useState(0)
   const[c,setC] = useState(0)
   function fun1(e)
   {
        setA(e.target.value)
   }
   function fun2(e)
   {
    setB(e.target.value)
   }
   function add(e)
   {
      var c = parseInt(a) + parseInt(b)
      setC(c)
     e.preventDefault()

   }
    return (<div>

       <form>
         <input type="text" onChange={fun1} placeholder="Enter first number" />
         <br/>
         <input type="text" onChange={fun2} placeholder="Enter second number" />
         <br/>
         <input type="submit" onClick={add} value="ADD" />
        </form>
        {c}
    </div>)
}

export default Hello;

2)   Class Component:-

the class component is used to contain the program code of react component using class and object patterns.

it provides the class pattern to implement component code, we can create a separate section to initialize data members and form attributes under the constructor \and init block. we can implement all features of oop's to create 

1) class-based component.

class Classname extends React. Component

{

       render()

       {

           return ( 


           )

       }

}

Example of class based component in React-JS

import React from "react";

export class Welcome extends React.Component
{
    render()
    {
        return(
         <div>
             <p>Welcome in Class Component in React JS</p>
         </div>
        );
    }
}

Code of index.js

import {Welcome} from './Welcome';

//const x = 11
//var result = <p>{ x%2==0?"even":"odd"}</p>
ReactDOM.render(
  <React.StrictMode>
    <Welcome />
  </React.StrictMode>,
  document.getElementById('xyz')
);

Addition program in REACT JS:-

Addition program using local instance variable

import React from "react";

export class Welcome extends React.Component
{
    render()
    {
        var a=10;
        var b=20;
        var c=0;
        this.c = a+b;
        return(
         <div>
             <p>{this.c}</p>
         </div>
        );
    }
}

Addition Program using global instance variable:-

import React from "react";

export class Addition extends React.Component

{

    state = {

        a: 100,

        b: 200,

        c:0

      };

       constructor()

   {

     super();

       }

   render()

   {

    const { a, b } = this.state;

    //console.log(this.state) ; 

     this.state.c=a+b;

    return(

       <div>

       <p>{this.state.a+this.state.b}</p>

       <p>{a+b}</p>

       <p>{this.state.c}</p>

       </div>

       )

   } 

}

index.js file:-

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import {Addition} from './Addition'

import reportWebVitals from './reportWebVitals';

ReactDOM.render(

  <React.StrictMode>

    <Addition />

  </React.StrictMode>,

  document.getElementById('root')

);

// If you want to start measuring performance in your app, pass a function

// to log results (for example: reportWebVitals(console.log))

// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals

reportWebVitals();

What is JSX Syntax:-

JSX stands for JavaScript XML.JSX allows us to write HTML in React.JSX makes it easier to write and add HTML in React.

Coding JSX with HTML

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.

JSX converts HTML tags into react elements.

Example 1

JSX:

const myelement = <h1>Welcome in  JSX!</h1>;

ReactDOM.render(myelement, document.getElementById('root'));


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

const myelement = <h1>Welcome in  JSX!</h1>;
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Example 2

Without JSX:

const myelement = React.createElement('h1', {}, 'I do not use JSX!');

ReactDOM.render(myelement, document.getElementById('root'));

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';

const myelement = React.createElement('h1', {}, 'I do not use JSX!');
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Expressions in JSX

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

const myelement = <p>Result is {100+200}</p>
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

Inserting a Large Block of HTML

To write HTML on multiple lines, put the HTML inside parentheses:

Example

Create a list with three list items:

const myelement = (

  <ul>

    <li>C</li>

    <li>CPP</li>

    <li>JAVA</li>

  </ul>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<ul><li>C</li><li>CPP</li><li>DS</li><li>Java</li></ul>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Example

Wrap two paragraphs inside one DIV element:

const myelement = (

  <div>

    <p>I am a paragraph.</p>

    <p>I am a paragraph too.</p>

  </div>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<div><p>Hello</p><p>Hi</p></div>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.

Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM. A fragment looks like an empty HTML tag: <></>. The fragment is the default container of react JS.

Wrap two paragraphs inside a fragment:

const myelement = (

  <>

    <p>I am a paragraph.</p>

    <p>I am a paragraph too.</p>

  </>

);

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



const myelement = (<><p>Hello</p><p>Hi</p></>)
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Elements Must be Closed

JSX follows XML rules, and therefore HTML elements must be properly closed.

Example

Close empty elements with />

const myelement = <input type="text" />;

Attribute class = className

The class attribute is a much-used attribute in HTML, but since JSX is rendered as JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to use it in JSX.Use attribute className instead.

JSX solved this by using className instead. When JSX is rendered, it translates className attributes into class attributes.

Example

Use attribute className instead of class in JSX:

const myelement = <h1 className="myclass">Hello World</h1>;

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';



// myelement = (<><p>Hello</p><p>Hi</p></>)
const myelement = <input type="text" className="ram" />;
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(myelement,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Write .css block:-

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
    monospace;
}

.ram
{
  background-color: brown;
}

 Conditions - if statements

React supports if statements, but not inside JSX.

To be able to use conditional statements in JSX, you should put the if statements outside of the JSX, or you could use a ternary expression instead:

Option 1:

Write if statements outside of the JSX code:

Example

Write "Hello" if x is less than 10, otherwise "Goodbye":

const x = 5;

let text = "Goodbye";

if (x < 10) {

  text = "Hello";

}

const myelement = <h1>{text}</h1>;

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';


const x = 10
var result = ""
if(x%2==0)
{
  result = "even"
}
else
{
  result = "odd"
}
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(result,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Option 2:

Use ternary expressions instead:

Example

Write "Hello" if x is less than 10, otherwise "Goodbye":

const x = 5;

const myelement = <h1>{(x) < 10 ? "Hello" : "Goodbye"}</h1>;


import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Hello from './Hello'
import Addition from './Addition'
import SI from './SI'
import Operation from './Operation';
import reportWebVitals from './reportWebVitals';


const x = 11
var result = <p>{ x%2==0?"even":"odd"}</p>
/*ReactDOM.render(
  <React.StrictMode>
    <Operation />
  </React.StrictMode>,
  document.getElementById('xyz')
);*/
ReactDOM.render(result,document.getElementById('xyz'));

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();


Post a Comment

0 Comments