EXAMPLES - HTML, CSS, JAVASCRIPT, REACTJS
EXAMPLES - HTML, CSS, JAVASCRIPT
LISTING.HTML
<html> <head> <title></title> </head> <body> <h3>ordered list</h3> <ol type="i"> <li>kolkata</li> <li>howrah</li> <li>dankuni</li> <li>kalyani</li> <li>dunlop</li> </ol> <h3>unordered list</h3> <ul type="square"> <li>kolkata</li> <li>howrah</li> <li>dankuni</li> <li>kalyani</li> <li>dunlop</li> </ul> <h3>Nested List</h3> <ol type="i"> <li>West Bengal <ul type="square"> <li>kolkata</li> <li>howrah</li> </ul> </li> <li>Assam <ul type="circle"> <li>gwahati</li> <li>dispur</li> </ul> </li> <li>Gujrat <ul type="square"> <li>ahmadabad</li> </ul> </li> <li>Tamil Nadu <ul> <li>chennai</li> </ul> </li> </ol> </body> </html>
HYPERLINK EXAMPLE 2:
<!DOCTYPE html> <html> <head> <title>hyperlink</title> </head> <body> <h2>Text Hyperlink</h2> <a href='ex_jul_6_1.html'>click here to visit</a> <br> <h2>Image hyperlink</h2>.. <a href='https://www.ejobindia.com'><img src="tenor.gif" width="10%" height="10%"/></a> <br><br> </body> </html>
DL DD DT EXAMPLE3:
<html> <head> <title></title> </head> <body> <dl> <dt>java:</dt> <dd>it is a oops lang</dd> <dt>php:</dt> <dd>it is a scripting lang</dd> <dt>react:</dt> <dd>it is a frontend framework</dd> <dt>angular:</dt> <dd>it is a mvc frontend framework</dd> </dl> </body> </html>H1-H6 P BR IMG EMBED EXAMPLE 4:
<html> <head> <title></title> </head> <body> <h1>welcome heading 1</h1> <h2>welcome heading 2</h2> <h3>welcome heading 3</h3> <h4>welcome heading 4</h4> <h5>welcome heading 5</h5> <h6>welcome heading 6</h6> <p>Hello this is <mark>my first paragraph.</mark><b>Welcome everybody to this class</b></p> <p><i><b>Hope everybody like the class.</b></i> We will enjoy <u>react js course</u></p> <p>Thank you . <strong>Visit again</strong></p> <p><sup><b>React js</b></sup> is very interesing to learn. WE will <sub>enjoy the course.</sub></p> <p>I like to do <del>web design</del><ins>web development</ins> coding.</p> <br> <!-- <img src="img111.jpg" width="30%" height="35%" alt="Sorry unable to load!" /> <br><br> <img src="E:\\PERSONAL_DOCS\\Krishna_wallpaper\\Gopal2.jpg" width="30%" height="20%" alt="sorry unable to load" /> <br><br> <img src="https://www.esa.int/var/esa/storage/images/esa_multimedia/images/2019/03/rainy_weather/19299886-1-eng-GB/Rainy_weather.jpg" width="30%" height="35%" alt="sorry unable to load" /> --> <br><br> <embed src="tenor.gif" width="30%" height="30%"></embed> <br><br> <embed src="https://www.youtube.com/embed/O5hShUO6wxs" height="200" width="300"></embed> <br><br> <embed src="demo.pdf" height="300" width="300"></embed> <br><br> <embed src="img111.jpg" height="300" width="300"></embed> <br><br> </body> </html>OL LI UL LI OL LI UL LI DL DT DD EXAMPLE 5:
<html> <head> <title></title> </head> <body> <h3>Ordered Listing</h3> <ol type="i"> <li>welcome c</li> <li>welcome c++</li> <li>welcome php</li> <li>welcome java</li> </ol> <h3>Unordered Listing</h3> <ul type="square"> <li>welcome c</li> <li>welcome c++</li> <li>welcome php</li> <li>welcome java</li> </ul> <h3>Nested listing</h3> <ol> <li>Java <ul> <li>core java</li> <li>adv java</li> </ul> </li> <li>Php <ul> <li>core php</li> <li>adv php</li> </ul> </li> <li>Javascript <ul> <li>basic js</li> <li>adv js</li> </ul> </li> </ol> <h3>Description Listing</h3> <dl> <dt><b>PHP:</b></dt> <dd>it is a good programming lang to use</dd> <dt><b>JAVA:</b></dt> <dd>it is a oops lang</dd> <dt><b>REACT JS:</b></dt> <dd>it is a frontend framework in javascript</dd> </dl> </body> </html>TABLE TR TH TR TD EXAMPLE 6:
<html> <head> <title></title> </head> <body> <table border="1" bgcolor="lightgreen" width="50%" cellspacing="5px" cellpadding="10px"> <caption><b>EMP DATA INFO:</b></caption> <tr> <th>EMP_ID</th> <th>EMP_NM</th> <th>EMP_DEPT</th> <th>EMP_AGE</th> </tr> <tr> <td>100</td> <td>AMIT JANA</td> <td>PHYSICS</td> <td>20</td> </tr> <tr> <td>101</td> <td>SOURAV DEY</td> <td>MATHS</td> <td>22</td> </tr> </table> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------HTML EXAMPLES (FINAL PART)
FORM EXAMPLE 1:<html> <head> <title></title> </head> <body> <form name="fm"> <label>ENTER NAME:</label> <input type="text" name="nm" placeholder="name plz" required> <br><br> <label>ENTER PASSWORD:</label> <input type="password" name="pwd" placeholder="pwd plz" required> <br><br> <label>ENTER AGE:</label> <input type="number" name="age" placeholder="Age plz" required> <br><br> <label>ENTER DOB:</label> <input type="date" name="dob" placeholder="MM-DD-YYYY" required> <br><br> <label>SELECT GENDER:</label> <input type="radio" name="gen" value="MALE" required>M <input type="radio" name="gen" value="FEMALE" required>F <br><br> <label>ENTER EMAIL:</label> <input type="email" name="em" placeholder="xxx@xxx.xxx" required> <br><br> <label>SELECT CITY:</label> <select name="city" required> <option value="">SELECT CITY</option> <option value="kolkata">kol</option> <option value="mumbai">mum</option> <option value="chennai">chn</option> <option value="assam">assm</option> <option value="howrah">hwh</option> <option value="sealdah">sldh</option> </select> <br><br> <label>SELECT JOB TYPE:</label> <select name="job" multiple required> <option value="full-time">ft</option> <option value="part-time">pt</option> <option value="contructual">conct</option> <option value="public sector">psu</option> <option value="private sector">pv</option> <option value="education">edu</option> </select> <br><br> <label>SELECT EDUCATIONAL DEGREE:</label> <input type="checkbox" name="edu" value="b.tech">B.E <input type="checkbox" name="edu" value="m.tech">M.E <input type="checkbox" name="edu" value="graduate" required>GRAD <input type="checkbox" name="edu" value="post graduate">P.G <input type="checkbox" name="edu" value="management">MBA <br><br> <label>ENTER REMARKS:</label> <textarea name="remk" cols="15" rows="5" placeholder="Type something..." required></textarea> <br><br> <label>Upload Photo:</label> <input type="file" name="upl" required> <br><br> <input type="submit" value="REGISTER"> <input type="reset" value="RESET"> </form> </body> </html>COLSPAN TABLE TR TD EXAMPLE 2:
<html> <head> <title></title> </head> <body> <table border="1" bgcolor="lightgreen" width="50%" cellspacing="5px" cellpadding="10px"> <tr> <th>emp_id</th> <th>emp_nm</th> <th>mob1</th> <th>mob2</th> </tr> <tr> <td>100</td> <td>ss</td> <td colspan="2">23456</td> </tr> <tr> <td>101</td> <td>sk</td> <td>123</td> <td>345</td> </tr> <tr> <td>102</td> <td>sg</td> <td colspan="2" rowspan="2">345678</td> </tr> <tr> <td>103</td> <td>sj</td> </tr> <tr> <td>104</td> <td>skjh</td> <td colspan="2">0987</td> </tr> </table> </body> </html>ROWSPAN TABLE TR TD EXAMPLE 3:
<html> <head> <title></title> </head> <body> <table border="1" bgcolor="lightgreen" width="50%" cellspacing="5px" cellpadding="10px"> <tr> <th>NAME</th> <th>LOCATION</th> <th>GENDER</th> </tr> <tr> <td>Suraj</td> <td rowspan="2">kolkata</td> <td rowspan="2">Male</td> </tr> <tr> <td>Rohit</td> </tr> <tr> <td>Sara</td> <td rowspan="2">Pune</td> <td rowspan="3">Female</td> </tr> <tr> <td>Tuli</td> </tr> <tr> <td>Seema</td> <td>Patna</td> </tr> </table> </body> </html>COLSPAN & ROWSPAN EXAMPLE 4:
<html> <head> <title></title> </head> <body> <table border="1" bgcolor="lightpink" width="40%"> <tr> <th>name</th> <th>loc1</th> <th>loc2</th> </tr> <tr> <td>aa</td> <td colspan="2">kolkata</td> </tr> <tr> <td>bb</td> <td colspan="2" rowspan="2">Howrah</td> </tr> <tr> <td>cc</td> </tr> <tr> <td>dd</td> <td>dankuni</td> <td>dumdum</td> </tr> <tr> <td>ee</td> <td colspan="2">sealdah</td> </tr> </table> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------CSS concept , Examples (PART 1)EXAMPLE 1:
<html> <head> <style> img { opacity: 0.5; border: 5px inset; border-color: blueviolet; border-radius: 25px; } img:hover { opacity: 1.0; border-color: green; width: 60%; height: 60%; } </style> </head> <body> <center> <h1>Image Transparency</h1> <p>The opacity property is often used together with the :hover selector to change the opacity on mouse-over:</p> <img src="https://thumbs.dreamstime.com/b/merry-christmas-happy-new-year-12013550.jpg" alt="Sorry unable to load" width="30%" height="30%"> </center> </body> </html>EXAMPLE 2:
<html> <head> <style> table { border-collapse:collapse; width: 50%; height: 40%; border: 5px double green; } td { text-align: center; padding: 5px; font-family: cursive; font-size: 20px; } th { background-color:lightgreen; color: blue; text-align: center; padding: 10px; font-family: sans-serif; } tr:nth-child(even){background-color: yellow; color: brown;} tr:nth-child(odd){background-color: lightpink;color: green;} </style> </head> <body> <table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Savings</th> </tr> <tr> <td>Peter</td> <td>Griffin</td> <td>$100</td> </tr> <tr> <td>Lois</td> <td>Griffin</td> <td>$150</td> </tr> <tr> <td>Joe</td> <td>Swanson</td> <td>$300</td> </tr> <tr> <td>Cleveland</td> <td>Brown</td> <td>$250</td> </tr> </table> </body> </html>EXAMPLE 3:
<html> <head> <style> ol { background:lightgreen; padding: 10px; width:20% } ul { background: yellow; padding: 20px; width:20%; } ol li { background:yellow; padding: 5px; margin: 5px; color: red; font-style:italic ; } ul li { background: lightgray; margin: 10px; color: green; padding: 5px; } </style> </head> <body> <ol type="I"> <li>West Bengal</li> <li>Assam</li> <li>Gujrat</li> <li>Tamil Nadu</li> <li>Punjab</li> </ol> <ul type="square"> <li>c</li> <li>c++</li> <li>java</li> <li>php</li> <li>python</li> </ul> </body> </html>EXAMPLE 4:
<!DOCTYPE html> <html> <head> <title></title> <style> p{ color:brown; background-color:yellow; text-align:center; font-size: 20px; font-style: italic; width: 30%; } h3{ color: green; text-align: center; } #p1{ color: red; background-color: green; text-align: left; } .pcls{ color: pink; background-color: blue; text-align: right; } </style> </head> <body> <h3 class="pcls">Welcome to Home</h3> <p>Hello this is first line</p> <p id="p1">Hello this is second line</p> <p class="pcls">hello this is third line</p> <span class="pcls">Thank you</span> </body> </html>EXAMPLE 5:
<html> <head> <title></title> </head> <body> <h3 style="color:red;background-color:yellow;text-align:center;">Welcome to css</h3> <p style="color:brown;font-style:italic;text-align:left;">Hello this is our first css class</p> <h4 style="color:green;text-align:right;font-style:italic;">Thank you</h4> </body> </html>EXAMPLE 6:
<html> <head> <style> .dotted {border-style: dotted;} .dashed {border-style: dashed;} .solid {border-style: solid;} .double {border-style: double;} .groove {border-style: groove;} .ridge {border-style: ridge;} .inset {border-style: inset;} .outset {border-style: outset;} </style> </head> <body> <p class="dotted">A dotted border.</p> <br> <p class="dashed">A dashed border.</p> <br> <p class="solid">A solid border.</p> <br> <p class="double">A double border.</p> <br> <p class="groove">A groove border.</p> <br> <p class="ridge">A ridge border.</p> <br> <p class="inset">An inset border.</p> <br> <p class="outset">An outset border.</p> <br> </body> </html>EXAMPLE 7:
<html> <head> <title></title> </head> <body> <div style="color:brown;background-color:yellow;width:40%;border:5px solid red;text-align: center;"> <h3>WELCOME TO HOME PAGE</h3> </div> <div style="color:green;background-color:lightblue;font-style:italic;font-size: 30px;width: 40%;"> <p>Hello this is my home page. WElcome everybody</p> </div> <div style="color:red;background-color:lightpink;border:5px double green;width: 40%;"> <ul> <li>hello kolkata</li> <li>hello mumbai</li> <li>hello chennai</li> <li>hello goa</li> </ul> </div> </body> </html>EXAMPLE 8:
<html> <head> <title></title> </head> <body> <h3 style="color:red;background-color:yellow;text-align:center;font-size: 35px;">Welcome to css class</h3> <p style="color:green;background-color:lightpink;font-size:30px;border:5px solid brown;">Hello good morning . This is my first css class</p> <h4 style="color:brown;font-style:italic;text-align:center;font-size: 30px;">Thank you</h4> </body> </html>EXAMPLE 9:
<html> <head> <style> table { border-collapse:collapse; width: 50%; } th, td { padding: 8px; text-align: center; border-bottom: 2px dashed red; } tr:nth-child(even){background-color: lightgreen; color: brown;} tr:nth-child(odd){background-color: lightpink;color: green;} tr:nth-child(even):hover{background-color:lightyellow;color: pink;font-style: italic;font-size: 25px;} tr:nth-child(odd):hover{background-color: lightskyblue;color: orange;font-style: italic;font-size: 25px;} p:hover{background-color: lightskyblue;color: orange;text-align: center;font-size: 25px;} </style> </head> <body> <h2>Hoverable Table</h2> <p>Move the mouse over the table rows to see the effect.</p> <table> <tr> <th>First Name</th> <th>Last Name</th> <th>Points</th> </tr> <tr> <td>Peter</td> <td>Griffin</td> <td>$100</td> </tr> <tr> <td>Lois</td> <td>Griffin</td> <td>$150</td> </tr> <tr> <td>Joe</td> <td>Swanson</td> <td>$300</td> </tr> <tr> <td>Cleveland</td> <td>Brown</td> <td>$250</td> </tr> </table> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------CSS Examples (FINAL PART)EXAMPLE 1:#div1{ position:absolute; top:150px; left:600px; } body{ background:lightblue; } img { opacity: 0.5; border: 5px dashed red; border-radius: 10px; } img:hover { opacity: 1.0; width: 600px; } #div2{ position:absolute; top:450px; left:100px; } .li_items{ display:inline-block; background-color:green; height:25px; width:150px; text-align:center; padding-top:10px; border: 2px inset brown; border-radius: 20px; } a{ text-decoration: none; } .li_items:hover{ background-color:yellow; height: 30px; width: 160px; color: purple; font-size: 30px; font-style: italic; } #div3{ position:absolute; top:10px; left:100px; width:800px; height:100px; } .search{ width:400px; height:40px; border:red dotted 2px; border-radius:20px; } .search:hover{ background-color:lightgreen; } .button1{ height:40px; background-color:#999; color:#03F; border-radius:10px; border: 5px dashed green; } .button1:hover{ background-color:lightyellow; color: red; font-size: 25px; }EXAMPLE 2:<html> <head> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="div1"> <img src="img1.jpg" width="500" height="250" /> </div> <div id="div2"> <ul> <li class="li_items"><a href="#">About Us</a></li> <li class="li_items"><a href="#">Contact Us</a></li> <li class="li_items"><a href="#">Sign In</a></li> <li class="li_items"><a href="#">Log Out</a></li> </ul> </div> <div id="div3"> <form> <input type="text" placeholder="Search Items" class="search" /> <input type="submit" value="Submit" class="button1" /> </form> </div> </body> </html>EXAMPLE 3:<!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 2px; padding: 2px; overflow: hidden; background-color:yellow; } li { float: left; } .li_item{ float: right; } li a { display: inline-block; color: green; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover { background-color:lightblue; color: red; } </style> </head> <body> <ul> <li><a href="borders.html">Home</a></li> <li><a href="#news">News</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> <li class="li_item"><a href="#about">LOGIN</a></li> <li class="li_item"><a href="#about">LOGOUT</a></li> </ul> </body> </html>EXAMPLE 4:<!DOCTYPE html> <html> <head> <style> .container { position: relative; /*border: 2px solid black;*/ } .black-box { position: relative; z-index: 1; border: 2px solid black; height: 100px; margin: 30px; background-color: yellow; } .gray-box { position: absolute; z-index: 3; /* gray box will be above both green and black box */ background: lightgray; height: 60px; width: 70%; left: 50px; top: 50px; } .green-box { position: absolute; z-index: 2; /* green box will be above black box */ background: lightgreen; width: 35%; left: 270px; top: -15px; height: 100px; } </style> </head> <body> <h1>Z-index Example</h1> <p>An element with greater stack order is always above an element with a lower stack order.</p> <div class="container"> <div class="black-box">Black box (z-index: 1)</div> <div class="gray-box">Gray box (z-index: 3)</div> <div class="green-box">Green box (z-index: 2)</div> </div> </body> </html>EXAMPLE 5:<html> <head> <style> .flex-container { display: flex; align-items: stretch; background-color:yellow; position: relative; } .flex-container div { background-color: DodgerBlue; color: white; margin: 15px; text-align: center; line-height: 35px; font-size: 30px; position:relative; } </style> </head> <body> <div class="flex-container"> <div> <ul> <li>This is the flex concept of css. This is very useful concept</li> <li>This is the flex concept of css. This is very useful concept</li> <li>This is the flex concept of css.</li> <li>This is the flex concept of css.</li> </ul> </div> <div > <ol> <li>This is the flex concept of css. This is very useful concept</li> <li>This is the flex concept of css. This is very useful concept</li> <li>This is the flex concept of css.</li> <li>This is the flex concept of css.</li> </ol> </div> <div> <img src="./img1.jpg" width="70%" height="50%"> </div> </div> </body> </html>EXAMPLE 6:<!DOCTYPE html> <html> <head> <style> div.relative { position: relative; width: 400px; height: 200px; border: 3px solid #73AD21; } div.absolute { position: absolute; top: 80px; right: 10px; width: 200px; height: 100px; border: 3px solid #73AD21; } .test{ position: absolute; width: 200px; height: 100px; border: 3px solid #73AD21; top: 400px; left: 300px; } div.fixed { position: fixed; bottom: 30px; right: 10px; width: 300px; border: 3px solid #73AD21; } </style> </head> <body> <h2>position: absolute;</h2> <p>An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed):</p> <p> Absolute positioned elements are removed from the normal flow, and can overlap elements.</p> <div class="relative">This div element has position: relative; <div class="absolute">This div element has position: absolute;</div> </div> <div class="test"> Single division with absolute position </div> <div class="fixed"> This div element has position: fixed; </div> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Basic Javascript Examples (PART 1)EXAMPLE 1:<!DOCTYPE html> <html> <head> <title></title> <script> document.write("<h2 style='color:red;'>Welcome to javascript</h2>") document.write("<img src='img1.jpg' width='50%' height='40%' alt='sorry'/><br>") document.write("<h3>Thank you</h3>"); document.write("hello this is javascript"); </script> </head> <body> </body> </html>EXAMPLE 2:<html> <head> <script> var x = window.prompt("enter name","") var y=window.prompt("enter location "," ") var z=window.prompt("enter age "," ") document.write("<h2 style='color:red;'> hello "+x+" welcome to "+y+" you are "+z+" years !</h2>") </script> </head> <body> </body> </html>EXAMPLE 3:<html> <head> <script> if(window.confirm("Do you agree to view?")) { document.write("<img src='img1.jpg' width='30%' height='30%'>") document.write("<br><br>") document.write("<img src='img2.jpg' width='30%' height='30%'>") document.write("<h2 style='color:red;'>Thank you</h2>") } else { window.alert("Window will quit!") window.close() } </script> </head> <body> </body> </html>EXAMPLE 4:<html> <head> <script> function myFun(x) { if(window.confirm("I agree to view?")) { document.write("<img src=img2.jpg width='30%' height='40%'>") document.write("Value is "+x); } else { window.alert("you want to quit?") window.close() } } </script> <body> <input type="button" value="click" onclick="myFun(10)"> </body> </html>EXAMPLE 5:<html> <head> <script> function myAge() { var name=document.f1.t1.value var age=document.f1.t2.value document.getElementById('head3').innerHTML="hello "+name+" your age is "+age+" years" } </script> </head> <body> <form name="f1"> ENTER NAME : <input type="text" name="t1" placeholder="Enter name"> <br><br> ENTER AGE : <input type="number" name="t2" placeholder="Enter age"> <br><br> <input type="button" value="SHOW" onClick="myAge()"> </form> <br> <h3 id="head3" style="color: red;">Coming soon.....</h3> </body> </html>EXAMPLE 6:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <script> var num=window.prompt("Enter number :"," "); // var i=1; // do // { // var m=num*i; // document.write(m+" "); // i++; // } // while(i<=10); // while(i<=10) // { // var m=num*i; // document.write(m+" "); // i++; // } for(var i=1;i<=10;i++) { var m=num*i; document.write(m+" "); } // var f=1; // for(var i=1;i<=num;i++) // { // f=f*i; // } // document.write("The factorial is :"+f+"<br>"); // } </script> </head> <body> </body> </html>EXAMPLE 7:Javascript : Javascript 2 types : 1. Internal javascript : <html> <head> <script> ---javascript coding ---- </script> </head> <body> <script> ---javascript coding ---- </script> </body> </html> 2. External Javascript : A seperate scripting file will be created with the extension of .js test.js ----> scripting file demo.html : <head> <script src="test.js"></script> //linking to html file </head> Implicit objects of javascript : implicit objects --- the objects which are already created by javascript for the purpose of using. document object --- (DOM) document object model document object refers to the web page of the application. write(); // to print in the web page + to execute the html code in javascript getElementById(); // this function is needed to access the html element using the id window object : the window object will refer the new tab in the browser. alert() // to display the alert message prompt() // to take input from user using a prompt box open() // open a new tab close() // close a exsisting tab boolean confirm() //to display a confirm box --- ok button --true cancel button--false variable in javascript : var keyword // it will be a global variable let keyword // it will be a local variable const keyword // to declare a constant no datatype concept in javascript var x=10; var x=25.67; var x="hello"; var x='j'; var x=true; //user defined function in javascript : <script> function abcd() { //body } abcd(); //call the function xxxxxxxx </script> <body> <input type="button" value="SHOW" onclick="abcd()"/> </body> // Fetching value from a html form : <script> syntax : document.form_name.element_name.value; var z = document.fm.nm.value; </script> <form name="fm"> ENTER NAME : <input type="text" name="nm" /> </form>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Basic Javascript Examples (PART 2)EXAMPLE 1:<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Validate Dropdownlist using JavaScript</title> <script> function ValidateDropdown() { var result = document.form1.ddlEducation.value; if (result == " ") { alert("Please Select Education"); } else { alert("Selected Value is: " + result); } } </script> </head> <body> <form name="form1"> Select Education: <select name="ddlEducation"> <option value=" ">--Select Education--</option> <option value="B.Tech">B.Tech</option> <option value="MCA">MCA</option> <option value="MBA">MBA</option> <option value="AGBSC">AGBSC</option> <option value="MBBS">MBBS</option> </select> <input type="button" value="Validate" onclick="ValidateDropdown()" /> </form> </body> </html>EXAMPLE 2<html> <head> <script> function myLogin() { var user=document.f1.t1.value var pass=document.f1.t2.value if(user!='madhu') { window.alert("invalid user id") document.f1.t1.focus() } else if (pass!='1234') { window.alert("hello "+user+" incorrect password") document.f1.t2.select() } else { document.getElementById("head2").innerHTML="hello "+user+" login successfully"; } } </script> </head> <body> <form name="f1"> user: <br> <input type="text" name="t1" placeholder="user id"> <br> password <br> <input type="password" name="t2" placeholder="password"> <br> <input type="button" value="login" onClick="myLogin()"> </form> <h2 id="head2" style="color:red;text-align:center;background-color:yellow;"></h2> </body> </html>EXAMPLE 3:<html> <head> <script> function ValidateForm() { if((document.feedback.gender[0].checked==false)&& (document.feedback.gender[1].checked==false)&& (document.feedback.gender[2].checked==false)) { window.alert("please choose your gender"); } else { var gen=document.feedback.gender.value; document.getElementById('res').innerHTML="Your gender is :"+gen; } } function resetval() { document.getElementById('res').innerHTML=" "; } </script> </head> <body> <form name="feedback"> your gender: <input type="radio" name="gender" value="male">male <input type="radio" name="gender" value="female">female <input type="radio" name="gender" value="others">others <input type="button" name="SubmitButton" value="submit" onClick="ValidateForm()"> <input type="reset" value="reset" onclick="resetval()"> </form> <p id="res"></p> </body> </html>EXAMPLE 4 :<html> <body> <script> function validateform(){ var name=document.myform.name.value; var password=document.myform.password.value; if (name==null||name=="") { window.alert("Name can't be blank"); return false; } else if(password.length<6) { alert("Password must be at least 6 characters long."); return false; } alert("submit successful"); return true; } </script> <body> <form name="myform" onsubmit="return validateform()" > Name: <input type="text" name="name"><br/> Password: <input type="password" name="password"><br/> <input type="submit" value="register"> </form> </body> </html>EXAMPLE 5:<html> <head> <script> function myFun() { var a=parseInt(document.form1.n1.value) var b=parseInt(document.form1.n2.value) var c=a+b var d=a-b var e=a*b var f=a/b document.getElementById('demo1').innerHTML="Summation is:"+c document.getElementById('demo2').innerHTML="Subtraction is:"+d document.getElementById('demo3').innerHTML="Multiplication is:"+e document.getElementById('demo4').innerHTML="Division is:"+f } </script> </head> <body> <form name="form1"> <table width="50%" height="220" border="1" bgcolor="lightgreen"> <tr> <td width="30%"> <input type="number" name="n1" placeholder="1st no"></td> <td id="demo1"></td> <td id="demo2"></td> </tr> <tr> <td> <input type="number" name="n2" placeholder="2nd no"></td> <td id="demo3"></td> <td id="demo4"></td> </tr> <tr> <td colspan="3" align="center"> <input type="button" name="b1" id="b1" value="submit" onclick="myFun()"> </td> </tr> </table> </form> </body> </html>EXAMPLE 6:<!DOCTYPE html> <html> <head> <script> function matchpass(){ var firstpassword=document.f1.password.value; var secondpassword=document.f1.password2.value; if(firstpassword==secondpassword){ alert("huraah password match!"); return true; } else{ alert("password must be same!"); return false; } } </script> </head> <body> <form name="f1" onsubmit="return matchpass()"> Password:<input type="password" name="password" /><br/> Re-enter Password:<input type="password" name="password2"/><br/> <input type="submit"> </form> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Basic Javascript (Final Part) ExamplesEXAMPLE 1:
<html> <head> <script> function evalGroup() { var len = document.radioForm.myRadio.length; var select=""; var count=0; for (var i=0; i<len; i++) { if (document.radioForm.myRadio[i].checked==true) { select=select+document.radioForm.myRadio[i].value+" "; count++; } } if (count==0) { alert("select any subject required"); } else { alert("Subjects selected : "+select); } } </script> </head> <body> <form name="radioForm"> SELECT YOUR SUBJECT : <br> PHP: <input type="checkbox" name="myRadio" value="php" /><br /> JAVASCRIPT: <input type="checkbox" name="myRadio" value="javascript" /><br /> ANDROID: <input type="checkbox" name="myRadio" value="android" /><br /> JAVA: <input type="checkbox" name="myRadio" value="java" /><br /><br /> .NET: <input type="checkbox" name="myRadio" value=".net" /><br /><br /> PYTHON: <input type="checkbox" name="myRadio" value="python" /><br /><br /> <input type="button" value="Validate" onclick="evalGroup()" /> </form> </body> </html>EXAMPLE 2:<!DOCTYPE html> <html> <head> <title></title> </head> <body> LENGTH : <input type="number" id="len"> <br> BREDTH : <input type="number" id="bred" oninput="area()"> <br> <h3 id="res"></h3> <br> HEIGHT : <input type="number" id="ht" oninput="vol()"> <br> <h3 id="res1"></h3> <script> function area() { var l=document.getElementById('len').value; var b=document.getElementById('bred').value; var ar=l*b; document.getElementById('res').innerHTML="AREA IS :"+ar; } function vol() { var l=document.getElementById('len').value; var b=document.getElementById('bred').value; var h=document.getElementById('ht').value; var v=l*b*h; document.getElementById('res1').innerHTML="VOLUME IS :"+v; } </script> </body> </html>EXAMPLE 3:<html> <body> Case 1 : <input type="text" id="demo" onkeydown="keydownFunction()" onkeyup="keyupFunction()"> <br><br> Case 2: <input type="text" name="val" onkeypress="myFunction()"> <br> <p id='p1'></p> <script> var x=0; function myFunction() { window.alert("You pressed a key inside the input field"); document.getElementById('p1').innerHTML="You pressed a key :"+(++x); } function keydownFunction() { document.getElementById("demo").style.backgroundColor = "red"; document.getElementById('p1').innerHTML="key is down!"; } function keyupFunction() { document.getElementById("demo").style.backgroundColor = "green"; document.getElementById('p1').innerHTML="key is up!"; } </script> </body> </html>EXAMPLE 4:<html> <head> <style> div { width: 100px; height: 100px; border: 1px solid black; margin: 10px; float: left; padding: 30px; text-align: center; background-color: lightgray; } p { background-color: white; } </style> </head> <body> <h3>This example demonstrates the difference between onmousemove, onmouseenter and onmouseover.</h3> <p>The onmousemove event occurs every time the mouse pointer is moved over the div element.</p> <p>The mouseenter event only occurs when the mouse pointer enters the div element. </p> <p>The onmouseover event occurs when the mouse pointer enters the div element, and its child elements (p and span).</p> <div onmousemove="myMoveFunction()"> <p>onmousemove: <br> <span id="demo">Mouse over me!</span></p> </div> <div onmouseenter="myEnterFunction()"> <p>onmouseenter: <br> <span id="demo2">Mouse over me!</span></p> </div> <div onmouseover="myOverFunction()"> <p>onmouseover: <br> <span id="demo3" style="color:red;"> Mouse over me! </span> </p> </div> <br><br> <p id="p1"></p> <div onmouseout="myOutFunction()"> <p>onmouseout: <br> <span id="demo4">Mouse over me!</span></p> </div> <script> var x = 0; var y = 0; var z = 0; var k = 0; function myMoveFunction() { document.getElementById("demo").innerHTML = ++z; } function myEnterFunction() { document.getElementById("demo2").innerHTML = ++x; } function myOverFunction() { document.getElementById("p1").innerHTML = "Mouseover hit count :"+(++y); } function myOutFunction() { document.getElementById("demo4").innerHTML = ++k; } </script> </body> </html>EXAMPLE 5:<!DOCTYPE html> <html> <head> <title></title> <script> function validate() { var count=0; var name="Selected Names are : "; var n = document.getElementById("nm_sel").options.length; for (var i = 0;i < n; i++) { if (document.getElementById("nm_sel").options[i].selected == true) { count++; name=name+document.getElementById("nm_sel").options[i].value+" "; } } if(count==0) { alert("select names required"); } else { alert(name); } } </script> </head> <body> Username:<br /> <select id="nm_sel" multiple> <option value="Siva">Siva</option> <option value="Raja">Raja</option> <option value="Roja">Roja</option> <option value="Laksh">Lakshanya</option> <option value="Vindhya">Vidhyaa</option> </select> <br /><br /> <button onclick="validate()">Validate</button> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Advance Js : String Functions , Array functions (part 1)EXAMPLE 1:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> let arr=[10,23.56,'b',"hello",true,"welcome"]; document.write("array length:"+arr.length+"<br>"); let st=arr.toString(); document.write("string length:"+st.length+"<br>"); document.write(st+"<br>"); let st2=arr.join(' '); document.write("string length:"+st2.length+"<br>"); document.write(st2+"<br>"); arr.push("react","java","hi",20.45); document.write(arr+"<br>"); document.write("pop :"+arr.pop()+"<br>"); document.write(arr+"<br>"); document.write("pop :"+arr.pop()+"<br>"); document.write(arr+"<br>"); </script> </body> </html>EXAMPLE 2:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> let st="hello welcome to react"; document.write("Length:"+st.length+"<br>"); document.write("slice1:"+st.slice(6,16)+"<br>"); document.write("slice2:"+st.slice(10)+"<br>"); document.write("substring:"+st.substring(5,15)+"<br>"); document.write("substring2:"+st.substring(11)+"<br>"); document.write("substr:"+st.substr(6,7)+"<br>"); let st2="i like react. react is good. react is easy REAct is new"; let st3=st2.replace("react","php"); document.write(st3+"<br>"); let st4=st2.replace(/react/g,"php"); document.write(st4+"<br>"); let st5=st2.replace(/react/ig,"php"); document.write(st5+"<br>"); let text11 = "Hello World!"; let text21 = text11.toUpperCase(); document.write(text21+"<br>"); let text1 = "HELLO World!"; // String let text2 = text1.toLowerCase(); document.write(text2+"<br>"); let s1="hello nice to talk"; let s2=" thank you"; let s3=" good bye"; let s4=s1.concat(s2,s3); document.write(s4+"<br>"); let s5=" Hello welcome to react "; document.write("len1:"+s5.length+"<br>"); let s6=s5.trim(); document.write("len2:"+s6.length+"<br>"); document.write("charAt: "+s1.charAt(6)+"<br>"); let ans="hello nice to talk to you have a good day"; let arr=ans.split(" "); document.write("Array: "+arr+"<br>"); let ans2="hello#nice#to#talk#you"; let arr2=ans2.split("#"); document.write("Array: "+arr2+"<br>"); let res="we like to read books. books are good. books make knowledge"; document.write("indexOf:"+res.indexOf("books")+"<br>"); document.write("lastIndexOf:"+res.lastIndexOf("books")+"<br>"); document.write("search:"+res.search("books")+"<br>"); document.write("indexOf2:"+res.indexOf("books",20)+"<br>"); document.write("startswith:"+res.startsWith("we like footballs")+"<br>"); document.write("endswith:"+res.endsWith("make is knowledge")+"<br>"); document.write("startswith:"+res.startsWith("to read",6)+"<br>"); document.write("endswith:"+res.endsWith("books make knowledge")+"<br>"); </script> </body> </html>EXAMPLE 3:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let len = txt.length; document.write("Length:"+len+"<br>"); //slice() extracts a part of a string and returns the extracted part in a new string. //The method takes 2 parameters: the start position, and the end position (end not included). let str = "Apple, Banana, Kiwi"; let part = str.slice(7, 13); let part2=str.slice(10); document.write(part+"<br>"+part2+"<br>"); //substring() is similar to slice(). let str2 = "Apple, Banana, Kiwi"; let part3 = str2.substring(9, 12); document.write(part3+"<br>"); //substr() is similar to slice(). //The difference is that the second parameter specifies the length of the extracted part. let str3="hello welcme to js"; document.write("substr :"+str3.substr(6,5)+"<br>"); //The replace() method replaces a specified value with another value in a string: //By default, the replace() method replaces only the first match: let text = "Please visit Microsoft and Microsoft!"; let newText = text.replace("Microsoft", "W3Schools"); document.write(newText+"<br>"); //To replace case insensitive, use a regular expression with an /i flag (insensitive): let text2 = "Please visit Microsoft and Microsoft!!"; let newText2 = text2.replace(/MICROSOFT/i, "W3Schools"); document.write(newText2+"<br>"); //To replace all matches, use a regular expression with a /g flag (global match): let text3 = "Please visit Microsoft and Microsoft and MICROSOFT!"; let newText3 = text3.replace(/Microsoft/ig, "W3Schools"); document.write(newText3+"<br>"); //Converting to Upper and Lower Case let text11 = "Hello World!"; let text21 = text11.toUpperCase(); let text1 = "Hello World!"; // String let text2 = text1.toLowerCase(); // text2 is text1 converted to lower //concat() joins two or more strings: let text1 = "Hello"; let text2 = "World"; let text3 = text1.concat(" ", text2); //The trim() method removes whitespace from both sides of a string: let text1 = " Hello World! "; let text2 = text1.trim(); //The charAt() method returns the character at a specified index (position) in a string: let text = "HELLO WORLD"; let char = text.charAt(0); //Converting a String to an Array A string can be converted to an array with the split() method: let st="hello @ how @ are @ you @ all @ now @ thank"; let arr=st.split('@'); document.write(arr[0]); //JavaScript String Search //The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: let str = "Please locate where 'locate' occurs!"; str.indexOf("locate"); //The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: let str = "Please locate where 'locate' occurs!"; str.lastIndexOf("locate"); //Both methods accept a second parameter as the starting position for the search: let str = "Please locate where 'locate' occurs!"; str.indexOf("locate", 15); //The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if the second parameter is 15, the search starts at position 15, and searches to the beginning of the string. let str = "Please locate where 'locate' occurs!"; str.lastIndexOf("locate", 15); //The search() method searches a string for a specified value and returns the position of the match: let str = "Please locate where 'locate' occurs!"; str.search("locate"); //JavaScript String startsWith() //The startsWith() method returns true if a string begins with a specified value, otherwise false: //syntax: string.startsWith(searchvalue, startindex) let text = "Hello world, welcome to the universe."; text.startsWith("world") // Returns false let text = "Hello world, welcome to the universe."; text.startsWith("world", 5) // Returns false let text = "Hello world, welcome to the universe."; text.startsWith("world", 6) // Returns true //JavaScript String endsWith() //The endsWith() method returns true if a string ends with a specified value, otherwise false: let text = "John Doe"; text.endsWith("Doe"); </script> </body> </html>EXAMPLE 4:<html> <body> <h2>Never Create Strings as objects.</h2> <p>Strings and objects cannot be safely compared.</p> <p>=== operator expects equality in both data type and value.</p> <p>== operator will be used when we will compare based on the value only</p> <p id="demo"></p> <p id="demo1"></p> <script> var x = "john"; // x is a string var y = new String("john"); // y is an object document.getElementById("demo").innerHTML = (x==y); document.getElementById("demo1").innerHTML = (x===y); </script> </body> </html>EXAMPLE 5:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h2>JavaScript Template Literals</h2> <p>Template literals allows variables in strings using back-ticks:</p> <p id="demo"></p> <script> let firstName = "John"; let lastName = "Doe"; let v=2; let text = `Welcome ${firstName} ${lastName} to the city kolkata! ${(v*10)+20}`; document.getElementById("demo").innerHTML = text; </script> </body> </html>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Advance Js : Array Built in Functions , Array callback functionsEXAMPLE 1:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> let arr=[10,23.56,'b',"hello",true,"welcome"]; document.write("array length:"+arr.length+"<br>"); let st=arr.toString(); document.write("string length:"+st.length+"<br>"); document.write(st+"<br>"); let st2=arr.join(' '); document.write("string length:"+st2.length+"<br>"); document.write(st2+"<br>"); arr.push("react","java","hi",20.45); document.write(arr+"<br>"); document.write("pop :"+arr.pop()+"<br>"); document.write(arr+"<br>"); document.write("pop :"+arr.pop()+"<br>"); document.write(arr+"<br>"); let arr2=[20,45.78,"hello","hi","php","hello","welcome","hello"]; document.write("indexof:"+arr2.indexOf("php")+"<br>"); document.write("indexof2:"+arr2.indexOf("hello")+"<br>"); document.write("lastindexof :"+arr2.lastIndexOf("hello")+"<br>"); document.write("indexof3:"+arr2.indexOf("hello",3)+"<br>"); document.write("indexof:"+arr2.indexOf("java")+"<br>"); let l=arr2.length; document.write("shift :"+arr2.shift()+"<br>"); document.write("Array :"+arr2+"<br>"); document.write(arr2[l-1]+"<br>"); arr2.unshift("c++"); document.write("Array :"+arr2+"<br>"); document.write(arr2[l-1]+"<br>"); arr2[0]="pune"; document.write("Array :"+arr2+"<br>"); delete arr2[3]; document.write("Array :"+arr2+"<br>"+arr2[3]+"<br>"); arr2[3]="kolkata"; document.write("Array :"+arr2+"<br>"+arr2[3]+"<br>"); document.write("slice :"+arr2.slice(2,7)+"<br>"); document.write("slice2 :"+arr2.slice(4)+"<br>"); var arr11 = ["Cecilie", "Lone"]; var arr21 = ["Emil", "Tobias", "Linus"]; var arr31 = ["Robin", "Morgan"]; var myChildren = arr31.concat(arr11, arr21); document.write(myChildren+"<br>"); document.write("splice :"+arr2.splice(3,2)+"<br>"); document.write("Array :"+arr2+"<br>"); document.write("splice :"+arr2.splice(4,0,"assam","goa")+"<br>"); document.write("Array :"+arr2+"<br>"); </script> </body> </html>EXAMPLE 2: ARRAY EVERY:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p id="demo"></p> <script type="text/javascript"> //The every() method checks if all array values pass a test. //It returns a boolean value true or false based on result. // <p>Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, it returns false.</p> var numbers = [11, 9, 3, 1, 31]; //var allOver18 = numbers.every(myFunction); //The find() method returns the value of the first array element that passes a test function. //var allOver18 = numbers.find(myFunction); //The findIndex() method returns the index of the first array element that passes a test function. var res = numbers.some(myFunction); //var res = numbers.every(myFunction); document.getElementById("demo").innerHTML = "Result: " + res; function myFunction(value) { if(value%2==0) { return true; } } </script> </body> </html>EXAMPLE 3: FILTER:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <h3 id='head3'></h3> <script> let arr=[1,3,5,8,11,15,20,40,44]; //let res=arr.filter(checknum); //let res=arr.find(checknum); let res=arr.findIndex(checknum); function checknum(value) { if(value%2==0) { return true; } } document.getElementById('head3').innerHTML=`The result is : ${res}`; </script> </body> </html>EXAMPLE 4: MAP_EX2
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <div id="show"></div> <script> var city = ["delhi","chennai","kolkata","pune","goa","patna","gaya","pune","howrah"]; var disp=""; var item=" "; disp="<table border='1' bgcolor='lightgreen' width='15%'><tr><th>CITYNAMES</th></tr>"; item=city.map(listing); disp+=item; disp+="</table>"; function listing(value) { return `<tr><td>${value}</td></tr>`; } document.getElementById('show').innerHTML=disp; </script> </body> </html>EXAMPLE 5: ARRAY_MAP
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p id="demo"></p> <script> //JavaScript Array.map() Creates a new array by performing a function on each array element. map() function can return the value performed on each element. var numbers1 = [1,2,3,4,5]; var res = numbers1.map(myFunction); document.getElementById("demo").innerHTML = res; function myFunction(value) { var f=1; for(var i=1;i<=value;i++) { f=f*i; } return (f); } // var text =["java","php","react","javascript","c++","c#.net"]; // var ans=""; // ans="<select>"; // ans+=text.map(myList); // ans+="</select>"; // document.getElementById("demo").innerHTML = ans; // function myList(value) // { // return `<option value=${value}>${value}</option>`; // } </script> </body> </html>EXAMPLE 6: FOREACH :
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p id="demo"></p> <script> var fruits, text; fruits = ["Banana", "Orange", "Apple", "Mango","watermelon","lichi","guava","lichi","cucumber","lichi2","chery","staberry","coconut","pineapple"]; text = "<ol type='a'>"; fruits.forEach(myFunction); text =text + "</ol>"; document.getElementById("demo").innerHTML = text; function myFunction(value) { text =text+`<li>${value}</li>`; } </script> </body> </html>EXAMPLE 7:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p id="demo"></p> <script> var fruits, text; fruits = ["Banana", "Orange", "Apple", "Mango","watermelon","lichi","guava","lichi","cucumber","lichi2","chery","staberry","coconut","pineapple"]; //fLen = fruits.length; text = "<select><option value=''>select fruit</option>"; fruits.forEach(myFunction); text =text + "</select>"; document.getElementById("demo").innerHTML = text; function myFunction(value) { text =text+`<option value=${value}>${value}</option>`; } </script> </body> </html>EXAMPLE 8: FILTER:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p id="demo"></p> <script> //filter() function Creates a new array with all array elements that passes a test. var numbers = [5, 49, 35, 26, 20,28,19,38]; var res = numbers.findIndex(myFunction); //var res = numbers.find(myFunction); //var res = numbers.filter(myFunction); document.getElementById("demo").innerHTML = res; function myFunction(value) { if(value>=15 && value<=25) { return true; } } </script> </body> </html>EXAMPLE 9 : FILTER 2:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var arr=[25,3,9,40,100,50,15]; var newarr=arr.filter(check); document.write("The new array :"+newarr+"<br>"); function check(value) { if(value%5==0 || value%10==0) { return true; } } </script> </body> </html>EXAMPLE 10: SOME:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p>Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, it returns false.</p> <script> function fnIsEven_some(arr){ return arr.some(function(element){ return(element %2 === 0); }); } document.write(fnIsEven_some([1,3,5])); document.write(fnIsEven_some([1,3,5,6])); </script> </body> </html>EXAMPLE 11: ARRAY FUN:
<html> <body> <h2>JavaScript Array Methods</h2> <h2>toString()</h2> <p>The toString() method returns an array as a comma separated string: The join() method also joins all array elements into a string. The pop() method removes the last element from an array: The push() method adds a new element to an array (at the end): The shift() method removes the first array element and "shifts" all other elements to a lower index. </p> <p id="demo"></p> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.pop(); fruits.push("Kiwi"); var x = fruits.shift(); //returns the string that was "shifted out": //The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements: fruits.unshift("Lemon"); //update array element by index fruits[0] = "Kiwi"; //elements can be deleted by using the JavaScript operator delete: delete fruits[0]; //The splice() method can be used to add new items to an array: //syntax : splice(index_to_add,no.of_element_remove,elements_to_add); //The splice() method returns an array with the deleted items: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 2, "Lemon", "Kiwi"); fruits.splice(0, 1); // Removes the first element of fruits //merging of arrays var arr1 = ["Cecilie", "Lone"]; var arr2 = ["Emil", "Tobias", "Linus"]; var arr3 = ["Robin", "Morgan"]; var myChildren = arr1.concat(arr2, arr3); //The slice() method slices out a piece of an array into a new array. //syntax: array.slice(start_index,End_index) var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1, 3); var citrus = fruits.slice(2); </script> </body> </html>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------Advance Js : (PART 2) ExamplesExample 1:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var check=()=>{ var n=window.prompt("Enter number",""); if(n%2==0) { document.write("Even number"); } else { document.write("odd number"); } } </script> <input type="button" value="Show" onclick="check()"> </body> </html>Example 2:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var factor=(num)=>{ for(var i=1;i<=num;i++) { if(num%i==0) { document.write("Factor is :"+i+"<br>"); } } } var n=window.prompt("Enter number",""); factor(n); </script> </body> </html>Example 3:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> //Declaring class class Employee { //Initializing an object constructor(iden,nm) { document.write("Constructor is called <br>"); this.id=iden; this.name=nm; } //Declaring method detail() { document.write(this.id+" "+this.name+"<br>"); } } //passing object to a variable var e1=new Employee(101,"Martin Roy"); var e2=new Employee(102,"Duke William"); e1.detail(); //calling method e2.detail(); </script> </body> </html>Example 4:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.</p> <br> <script type="text/javascript"> let a,b,rest; [a,b,...rest]=[10,20,30,40,50,"thank you"]; document.write(a+" "+b+"<br>"); document.write(rest+"<br>"); </script> </body> </html>Example 5:<html> <body> <p id="demo"></p> <script> // Create an object: var person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName+" "+this.id; } }; var person2 = { first: "Raj", last: "Khanna", id:5590, display : function(){ return this.first+" "+this.last+" "+this.id; }, vol:function(l,b,h){ return (l*b*h); } }; // Display data from the object: document.getElementById("demo").innerHTML ="Person object :"+person.fullName()+ "<br>person2 object :"+person2.display()+"<br> Volume :"+person2.vol(2,5,4); </script> </body> </html>Example 6:<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var obj={ id:10, name:'raj', emp1:{id:11,name:'ravi',age:20,loc:'howrah'}, emp2:{id:12,name:'rajesh',age:22,loc:'patna'} } document.write(obj.emp1.name+"....."+obj.emp2.name+"<br>"); document.write(obj.emp2.sal+"<br>"); //nested object document.write("Hello next line ....<br>"); document.write(obj?.emp3?.dept+"<br>"); document.write("Thank you"); // document.write("Emp1 name :"+obj?.emp1?.name+"<br>"); // document.write("Emp1 name :"+obj?.emp2?.id+"<br>"); // document.write("Emp1 name :"+obj?.emp1?.sal+"<br>"); // document.write("Emp2 Loc :"+obj?.emp3?.loc+"<br>"); // document.write("Thank you"); </script> </body> </html>Exanoke 7:
<html> <body> <h2>Object Notation in Javascript</h2> <p id="demo"></p> <script> var person = { firstName : "John", lastName : "Doe", age : 50, eyeColor : "blue", firstName:"Rajesh", }; person['email']="Jk@gmail.com"; person.age=45; document.getElementById("demo").innerHTML ="<ol><li>Firstname :"+person.firstName+"</li><li>Lastname :"+person.lastName+"</li><li>Age:"+person.age+"</li><li>Eye color:"+person.eyeColor+"</li><li>Email :"+person.email+"</li></ol>" </script> </body> </html>Example 8:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p> The optional chaining ‘?.’ is an error-proof way to access nested object properties, even if an intermediate property doesn’t exist. The optional chaining operator (?.) allows you to access the value of a property located deep within a chain of objects without explicitly checking if each reference in the chain is null or undefined. If one of the references in the chain is null or undefined, the optional chaining operator (?.) will short circuit and return undefined. </p> <script type="text/javascript"> const adventurer = { name: 'Alice', cat: { name: 'Dinah', colour:'brown' }, dog:{ name:'juby', color:'black' }, address:{city:'kolkata', state:["westbengal","gujrat","assam"], location:'gariahat'} }; const dogName = adventurer.dog.name; document.write(dogName+"<br>"); // (dogName=='undefined')?'tommy':dogName; document.write(adventurer?.cat?.colour+"<br>"); document.write(adventurer?.dog?.petname+"<br>"); document.write(adventurer?.rabbit?.colour?.petname+"<br>"); document.write(adventurer?.address?.city+"<br>"); document.write(adventurer?.address?.state+"<br>"); </script> </body> </html>Example 9:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <p>rest parameters are the variable arguments parameters which can take multiple arguments. rest parameters are passed by ... (three dots). they are passed at last with in a function with other normal parameters</p> <br> <!-- <script> function sumAll(...args) { let sum = 0; for (let i=0;i<args.length;i++) { sum=sum+args[i]; } return sum; } alert("The sum1 is : "+sumAll() ); alert("The sum2 is : "+sumAll(10,20,90,100) ); alert("The sum3 is : "+sumAll(10, 12, 13,30,50,40,100) ); </script> --> <!-- <script> function showName(firstName,lastName,...titles) { alert( firstName + ' ' + lastName ); for(let x=0;x<titles.length;x++) { alert(titles[x]); } } showName("Julius", "Caesar", "Consul", "Imperator","hello","kolkata"); </script> --> <!-- <script> function evencheck(...arg) { for(let i=0;i<arg.length;i++) { if(arg[i]%2==0) { alert(arg[i]); } } } evencheck(10,9,11,13,20,33,40); </script> --> <script> function isprime(...args) { for(let i=0;i<args.length;i++) { let flag=1; for(let j=2;j<args[i];j++) { if(args[i]%j==0) { flag=0; } } if(flag==1) { alert(args[i]); } } } isprime(2,3,10,11,13,15,19); </script> </body> </html>--------------------------------------------------------------------------------------------------------------------------------------------Advance Js (Part 3) ExamplesExample -1:
<html> <body> <h2>JavaScript addEventListener()</h2> <p>This example uses the addEventListener() method to attach a click event to a button.</p> <p>This example uses the addEventListener() method to add two click events to the same button.</p> <p>This example uses the addEventListener() method to add many events on the same button.</p> <p>This example demonstrates how to pass parameter values when using the addEventListener() method.</p> <button id="myBtn">Try it 1</button> <button id="myBtnnew">Try it 2</button> <button id="myBtn2">Try it 3</button> <button id="myBtn3">Try it 4</button> <script> document.getElementById("myBtn").addEventListener("click", function() { alert("Hello World!"); }); </script> <script> var x = document.getElementById("myBtnnew"); x.addEventListener("click", myFunction); x.addEventListener("click", someOtherFunction); function myFunction() { alert ("Hello World!"); } function someOtherFunction() { alert ("This function was also executed!"); } </script> <script> var x = document.getElementById("myBtn2"); x.addEventListener("mouseover", myFunction); x.addEventListener("click", mySecondFunction); x.addEventListener("mouseout", myThirdFunction); function myFunction() { document.getElementById("demo").innerHTML = "Moused over!<br>"; } function mySecondFunction() { document.getElementById("demo").innerHTML = "Clicked!<br>"; } function myThirdFunction() { document.getElementById("demo").innerHTML = "Moused out!<br>"; } </script> <p id="demo"></p> <script> var p1 = 5; var p2 = 7; document.getElementById("myBtn3").addEventListener("click", function() { myFunction(p1, p2); }); function myFunction(a,b) { var result = a * b; document.getElementById("demo").innerHTML = result; } </script> </body> </html>example -2<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p> ES6 has added spread property to object literals in javascript. The spread operator (…) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. </p> <script> // const user1 = { // name: 'Jen', // age: 22 // }; // const clonedUser = { ...user1 }; // console.log(clonedUser); const user1 = { fname: 'Jen', age: 22 }; const user2 = { lname: "Andrew", location: "Philadelphia" }; const mergedUsers = {...user1, ...user2,gen:'male',sal:12000}; console.log(mergedUsers) </script> </body> </html>example -3<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script> let arr1 = [1, -2, 3, 4]; let arr2 = [8, 3, -8, 1]; alert( "MAX VALUE :"+Math.max(...arr1, ...arr2) );//8 alert( "MIN VALUE :"+Math.min(...arr1, ...arr2) );//-8 //alert( "MAX VALUE :"+Math.max(1, -2, 3, 4, 8, 3, -8, 1) ); //alert( "MIN VALUE :"+Math.min(1, -2, 3, 4, 8, 3, -8, 1) ); let arr = [3, 5, 1]; let arr3 = [8, 9, 15]; let merged = [0, ...arr,2,...arr3]; alert("MERGED ARRAY :"+merged); //Clone Array Using Spread Operator //if you want to copy arrays so that they do not refer to the same array, you can use the spread operator. let arr1 = [ 1, 2, 3]; // copy using spread syntax let arr2 = [...arr1]; console.log(arr1); // [1, 2, 3] console.log(arr2); // [1, 2, 3] // append an item to the array arr1.push(4); console.log(arr1); // [1, 2, 3, 4] console.log(arr2); // [1, 2, 3] </script> </head> <body> <p>Spread syntax looks similar to rest parameters, also using ..., but does quite the opposite.</p> <p>Spread syntax converts an array to the list of elements when passed to functions</p> <p>rest parameters converts a collection of values into the array.</p> </body> </html>Example -4<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p>You can use call(), apply(), and bind() methods to tie a function into an object and call the function as if it belonged to that object.</p> <h3>call() :</h3> <p>The call() method invokes a function with a specified context. In other words, you can tie a function into an object as if it belonged to the object.</p> <h3>apply() :</h3> <p>The apply() method does the exact same as call(). The difference is that call() accepts an argument list, but apply() accepts an array of arguments.</p> <h3>bind() :</h3> <p>The bind() method is reminiscent of call() and apply(). But instead of executing a function immediately, bind() returns a function that can be executed later on.</p> <script> var obj = { num: 2 }; function add(a, b){ return this.num + a + b; } const resultCall = add.call(obj, 3, 5); //return the value directly const resultApply = add.apply(obj, [3, 5]); //return the value directly const funcBind = add.bind(obj, 3, 5) const resultBind = funcBind(); console.log(resultCall, resultApply, resultBind); </script> </body> </html>Example -5<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p> In javascript we can handle the runtime errors using the try , catch , finally blocks. Syntax try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result } </p> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { const message = document.getElementById("p01"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "is empty"; if(isNaN(x)) throw "is not a number"; if(x > 10) throw "is too high"; if(x < 5) throw "is too low"; message.innerHTML = "CORRECT INPUT IS :"+x; } catch(err) { message.innerHTML = "Input Error: " + err; } finally { document.getElementById("demo").value = ""; alert("Thank you"); } } </script> </body> </html>example -6<!DOCTYPE html> <html> <body> <p id="demo"></p> <p>Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope</p> <script> x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element var x; // Declare x </script> </body> </html>example -7<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <p>Like variables, the JavaScript engine also hoists the function declarations. This means that the JavaScript engine also moves the function declarations to the top of the script.</p> <script> let x = 20, y = 10; let result = add(x, y); console.log(result); function add(a, b) { return a + b; } </script> </body> </html>example- 8<!DOCTYPE html> <html> <body> <h2>JavaScript Regular Expressions</h2> <p><a href="https://www.w3schools.com/jsref/jsref_obj_regexp.asp">For more regerx patterns</a></p> <p id="demo"></p> <script> // let text = "Visit W3Schools"; // let pattern = /w3schools/i; // let text2 = "hello react hello REAct hello REACT"; // let pattern2=/React/ig; //let result = text.match(pattern); //let result = text2.match(pattern2); //A global search for the character "h" in a string: let text3 = "hello react hello REAct hello REACT"; let pattern3 = /React/ig; let result = text3.match(pattern3); document.getElementById("demo").innerHTML = result; </script> </body> </html>--------------------------------------------------------------------------------------------------------------------------------------------------------------Promise Concept , Async , await , Json methods , Json concept
Example 1:
<!DOCTYPE html> <html> <body> <h2>JavaScript async / await</h2> <p>Wait 3 seconds (3000 milliseconds) for this page to change.</p> <p>The word “async” before a function means one simple thing: a function always returns a promise.There’s another keyword, await, that works only inside async functions.The keyword await makes JavaScript wait until that promise settles and returns its result.</p> <h1 id="demo"></h1> <script> async function myDisplay() { let myPromise = new Promise(function(myResolve, myReject) { setTimeout(function() { myResolve("Welcome to EjobIndia!"); }, 5000); }); document.getElementById("demo").innerHTML = await myPromise; } myDisplay(); </script> </body> </html>Example 2:<!DOCTYPE html> <html> <body> <h2>JavaScript async / await</h2> <p></p> <h1 id="demo">Welcome</h1> <script> async function myDisplay() { let x=window.prompt("Enter the number",""); let myPromise = new Promise(function(myResolve, myReject) { if (x%2==0) { setTimeout(function() { myResolve("Even number received"); }, 5000); } else { setTimeout(function() { myResolve("Odd number received"); }, 5000); } }); document.getElementById("demo").innerHTML = await myPromise; } </script> <button onclick="myDisplay()">Click me</button> </body> </html>Example-3:A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. The constructor syntax for a promise object is: Syntax : let obj=new Promise(function(resolve,reject){ /*executor function*/ }); obj.then( function(){ /* for resolve callback*/ }) .catch( function(){ /*for reject callback*/ }) The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result. Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only inside the executor. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks: resolve(value) — if the job is finished successfully, with result value. reject(error) — if an error has occurred, error is the error object. The promise object returned by the new Promise constructor has these internal properties: state — initially "pending", then changes to either "fulfilled" when resolve is called or "rejected" when reject is called. result — initially undefined, then changes to value when resolve(value) called or error when reject(error) is called.Example- 4<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script> var promise = new Promise(function(resolve, reject) { const x = "hello"; const y = "welcome"; if(x == y) { resolve(); } else { reject(); } }); promise. then(function () { console.log('Success, You are a winner'); }). catch(function () { console.log('Some error has occured'); }); </script> </body> </html>Example- 5<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script> let val=prompt("Enter value",""); var promise = new Promise(function(resolve,reject) { if(val%2!=0) {reject('Promise Rejected Odd value')} else {resolve('Promise Accepted Even Value')} }); promise .then(function(successMessage) { console.log(successMessage); }) .catch(function(errorMessage) { console.log(errorMessage); }); </script> </body> </html>Example-6<!DOCTYPE html> <html> <head> <title> JavaScript | Convert array to JSON. </title> </head> <body style = "text-align:center;" id = "body"> <p id = "GFG_UP" style = "font-size: 16px;"> </p> <button onclick = "gfg_Run()"> Convert </button> <p id = "GFG_DOWN" style = "color:green;font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [34, 24, 31, 48,'hello',90.87,true]; el_up.innerHTML = "Array = [" +array+"]";; function gfg_Run() { el_down.innerHTML = "JSON_String = '"+JSON.stringify(array)+"'"; } </script> </body> </html>Example-7<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var j = '{"Name":"Krishna","Email": "kr@gmail.com", "CN": "12345"}'; //json string var data = JSON.parse(j); document.write(data.Email+"<br>"); document.write(data.Name+"<br>"); document.write(data.CN+"<br>"); </script> </body> </html>Example-8<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> </head> <body> <script> var j = {Name:"Krishna",Email: "XYZ", CN : 12345,gender:"MALE",age:22,id:10}; var data = JSON.stringify(j); document.write("<br>Convert string in JSON format using stringify() method<br>"); console.log("RESULT :",data); </script> </body> </html>Example -9JSON: JavaScript Object Notation. JSON is a syntax for storing and exchanging data. JSON Syntax Rules JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays[] JSON Strings Strings in JSON must be written in double quotes. Example { "name":"John" } JSON Numbers Numbers in JSON must be an integer or a floating point(decimal). Example { "age":30, "price":250.50 } JSON Objects Values in JSON can be objects. Example { "employee":{"name":"John","age":30,"city":"New York"} } Objects as values in JSON must follow the same rules as JSON objects. JSON Arrays Values in JSON can be arrays. Example { "employees":["John","Anna","Peter"] } JSON Booleans Values in JSON can be true/false. Example { "sale":true } JSON null Values in JSON can be null. Example { "middlename":null } ------------------------------------------------------------------ EXAMPLE OF JSON FILE : { "name":"raj", "loc":"kolkata", "age":25, "gender":"male", "avg marks":23.5678 "e1":{ "name":"John", "age":30, "city":"New York" }, "employee2":{ "name":"ravi", "age":35, "city":"kokata","active":true,"grade":null }, "employees":[ "John", "Anna", "Peter" ], "loc":["kolkata","pune","delhi"], "age":[20,25,30,35,40] }------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Node install , React App Install , Folder Structure Explain, Class Component Example
React Js is a frontend framework(library) of Javascript Framework v/s Library : Framework has an architecture (MVC) (model view controller) based on which a framework will work. Library has no such architecture.Library is just the collection of pre defined functions , classes , modules , packages which we can use for our coding purpose. React js is also a kind of library and not a framework because it has no such MVC architecture to work with. React js is developed by using ES6 (Ecma script version 6) Node js server. ---> It is the working runtime envirinment which is needed to run the javascript and react js application. we have to install the node js in our machine. Now we will create the React Js application folder structure. We will create a React workspace (folder) in which we will keep the react applications. To create a new react application we need to type the command : E:\React_Work>npx create-react-app app_name; click y to proceed ? (y/n) y enter press npx ---> node package execute app_name ---> rule ---> the appname must start with lowercase alphabet only. Happy Hacking ---> when we can see this message in the terminal then it is sure that our app folder is created. To start the app : E:\React_Work>cd sixthapp E:\React_Work\sixthapp>npm start this command will start the node server npm --> node package manager http:\\localhost:3000 Folder structure : node_modules ---> this folder contains all the pre installed modules which are provided by react js.Never edit this folder. package.json ---> this file contains the info of the pre installed modules and their version in the json format. src ---> this is our working folder in react app filename.js or .jsx ---> component (we will not call it as a file, we will call component) React js is known as a single page application. Php --- app --- home.php , login.php , register.php c app --- home.c , demo.c --- multi page app Single page application ----> a single page will always execute . App.js ----> src/App.js ---> this is the main component which always runs. home.js , login.js ----> this components can not run individually. we need to import the components to App.js and then run them from App.js The language we use in React coding is jsx. (combination of javascript + HTML) The component file extension can be .js or .jsx component is of 2 types : 1. Class component --- we will create a javascript class. 2. Functional component --- we will create a javascript function .(normal function) or (arrow function) http://localhost:3000/ 3000 --- default port command to stop the node server : ctrl+c ---- it will stop your node server Rule for Component file naming convention : 1.The extension of the file should be .js or .jsx 2.The component filename must start with uppercase alphabet. 3.The component filename and the component name should have the same name as per the convension. Home.js ----> component file Home --->name of my component. Login.js ----> component ---> Login
Test.js
import React from 'react'; class Test extends React.Component { render() { return( <div> <h3>Welcome to my class component</h3> <p>Hello this is my first component.</p> </div> ) } } export default TestApp.js
import logo from './logo.svg'; import './App.css'; import First from './components/First'; import Second from './components/Second'; import Third from './components/Third'; import Fourth from './components/Fourth'; import Stateex from './components/Stateex'; import Test from './components/Test'; function App() { return ( <div> {/* <First/> <Second/> <Third/> */} {/* <Fourth/> */} {/* <Stateex/> */} <Test/> </div> ); } export default App;------------------------------------------------------------------------------------------------------------------------------------Class components , State management , Concept , State update , Functional component concepttest5.jsimport React from 'react'; class Test5 extends React.Component { state={ len:'', bred:'' } valchng=(e)=>{ this.setState({[e.target.name]:[e.target.value]}); } calc=(e)=>{ let ar=this.state.len * this.state.bred; document.getElementById('head3').innerHTML='AREA IS : '+ar; } render() { return( <div> LENGTH: <input type='number' name='len' onChange={this.valchng}/> <br></br> BREADTH: <input type='number' name='bred' onChange={this.valchng}/> <br></br> <input type='button' value='Area' onClick={this.calc}/> <br></br> <h3 id='head3'>Value is coming soon </h3> </div> ) } } export default Test5statechng.jsimport React from 'react'; class Statechng extends React.Component { state={ name:'', email:'' } valchng=(e)=>{ this.setState({[e.target.name]:[e.target.value]}); } render() { return( <div> <ul type='square'> <li>NAME IS : {this.state.name}</li> <input type='text' name='name' onChange={this.valchng}/> <li>EMAIL IS : {this.state.email}</li> <input type='email' name='email' onChange={this.valchng}/> </ul> </div> ) } } export default Statechng;test4.jsimport React from 'react'; class Test4 extends React.Component { state={ id:10, name:'avishek', age:20, loc:'kolkata' } valchng=(e)=>{ this.setState({ id:20, name:'Sourav', age:25, loc:'Patna' }); } render() { return( <div> <table border='1' bgcolor='lightgreen' width='40%'> <tr> <th>ID</th> <th>NAME</th> <th>AGE</th> <th>LOCATION</th> </tr> <tr> <td>{this.state.id}</td> <td>{this.state.name}</td> <td>{this.state.age}</td> <td>{this.state.loc}</td> </tr> </table> <input type='button' value='UPDATE' onClick={this.valchng}/> </div> ) } } export default Test4test3.jsimport React from 'react'; const Test3=()=>{ return( <div> <h3>Hello this is functional component 2</h3> <p>Thank you</p> </div> ) } export default Test3test2.jsimport React from 'react'; function Test2() { return( <div> <h3>Welcome to functional component 1</h3> <p>Have a nice day!</p> </div> ) } export default Test2first.jsimport React from 'react'; class First extends React.Component { render() { return( <div> <h3>Hello this is my first class component</h3> <p>Thank you visit again</p> </div> ) } } export default First;------------------------------------------------------------------------------------------------------------------------------------CSS in React , constructor() in Class component , HTML forms in React componentForm4.jsimport React from 'react' class Form4 extends React.Component { constructor(props) { super(props); this.state = { username: '', age: '', errormessage: '' }; } myChangeHandler = (event) => { this.setState({[event.target.name]:[event.target.value]}); let nam = event.target.name; let val = event.target.value; let err = ''; if (nam === "age") { if (val ==="" || val ===null) { err = <strong style={{color:'red'}}>Your age must not be empty!</strong>; } else if(val<18 || val>25) { err = <strong style={{color:'red'}}>Your age must be between 18 to 25!</strong>; } } if(nam==="username") { if(val===""||val===null) { err = <strong style={{color:'red'}}>Your name must not be empty!</strong>; } } this.setState({errormessage: err}); } render() { return ( <form> <h1>Hello {this.state.username} {this.state.age}</h1> <p>Enter your name:</p> <input type='text'name='username' onChange={this.myChangeHandler}/> <p>Enter your age:</p> <input type='number' name='age' onChange={this.myChangeHandler}/> <br></br> {this.state.errormessage} </form> ); }} export default Form4FormTest.jsimport React from 'react' class Formtest extends React.Component { state={ uname:'', age:'', loc:'', result:'' } handleChange=(e)=>{ this.setState({[e.target.name]:[e.target.value]}) } showResult=(e)=>{ let ans='Welcome...'+this.state.uname+' Age is: '+this.state.age+' to your city: '+this.state.loc; this.setState({result:ans}) } render(){ return( <div> Name : <input type='text' name='uname' onChange={this.handleChange}/> <br></br> Age : <input type='number' name='age' onChange={this.handleChange}/> <br></br> Location : <input type='text' name='loc' onChange={this.handleChange}/> <br></br> <input type='button' value='show' onClick={this.showResult}/> <br></br> <h3 style={{color:'green'}}>{this.state.result}</h3> </div> ); } } export default FormtestForm3.jsimport React from 'react' class Form3 extends React.Component { constructor(props) { super(props); this.state = { username: '' }; } mySubmitHandler = (event) => { event.preventDefault(); //prevent the form from actually being submitted if(this.state.username) { alert("You are submitting " + this.state.username); } else { alert("Provide username....."); } } myChangeHandler = (event) => { this.setState({username: event.target.value}); } render() { return ( <form onSubmit={this.mySubmitHandler}> <h1>Hello {this.state.username}</h1> <p>Enter your name, and submit:</p> <input type='text' onChange={this.myChangeHandler}/> <input type='submit' value='Show'/> </form> ); } } export default Form3Style.css#div1{ color: blue; background-color: chartreuse; border: 2px solid green; width: fit-content; text-align: center; } .test{ font-size: 20px; font-style: italic; font-family:monospace; background-color:cyan; }Extcss.jsimport React from 'react' import './style.css'; class Extcss extends React.Component { render() { return( <div id='div1'> <h1 class='test'>Hello Style!</h1> <p class='test'>Add a little style!.</p> </div> ); } } export default ExtcssForm2.jsimport React from 'react' class Form2 extends React.Component { constructor(props) { super(props); this.state = { username: '' }; } myChangeHandler = (event) => { this.setState({username: event.target.value}); } render() { let header = ''; if (this.state.username) //Conditional Rendering { header = <h1>Hello {this.state.username}</h1>; } else { header = ''; } return ( <form> {header} <p>Enter your name:</p> <input type='text' onChange={this.myChangeHandler}/> </form> ); } } export default Form2Constructex.jsimport React from 'react' class Constructex extends React.Component { constructor(props) { super(props); //initialise of props this.state = { //initialise of state object brand: "Ford", model: "Mustang", color: "red", year: 1964 }; } changeColor = (event) => { this.setState({color: "blue", brand: "Hyundai", model:"i20", year:2020 }); } render() { return ( <div> <h1>My {this.state.brand}</h1> <p> It is a {this.state.color} <br></br> {this.state.model} from {this.state.year}. </p> <br></br> <button type="button" onClick={this.changeColor}>Change Info</button> </div> ); } } export default ConstructexCssEx.jsimport React from 'react' class CssEx extends React.Component { render() { const mystyle = { color: "green", backgroundColor: "DodgerBlue", padding: "10px", fontFamily: "Arial", textAlign:"center" }; return ( <div> <h1 style={{color: "red",backgroundColor: "lightblue"}}>Hello Inline Css Style!</h1> <p style={mystyle}>This is a style to add multiple css properties in internal Css</p> <h3 style={mystyle}>Thank you!</h3> </div> ); } } export default CssEx------------------------------------------------------------------------------------------------------------------------------------------------------------------HTML form validation in React , map() , List, Table, Dropdown , Keys , RefsRefSex.js
import React from 'react' class Refsex extends React.Component { constructor(props) { super(props); this.callRef = React.createRef(); //create a reference this.callRef2= React.createRef(); this.callRef3=React.createRef(); } addingRefInput=(e)=> { alert(this.callRef.current.value+"......."+this.callRef2.current.value); } textchng=(e)=>{ this.callRef.current.value="Have a nice day!!!!"; this.callRef3.current.innerText="Thank you visit again!"; } render() { return ( <div> ENTER NAME: <input type="text" ref={this.callRef} /> <br></br> ENTER DATE: <input type="date" ref={this.callRef2}/> <br></br> <input type="button" value="Click" onClick={this.addingRefInput} /> <br></br> <input type="button" value="Show" onClick={this.textchng} /> <br></br> <h2 ref={this.callRef3}>Welcome to this page!</h2> </div> ); } } export default RefsexKeys.js
import React from 'react' const data = [ {id:0, title :'Default',content:'select content'} , {id: 1, title: 'First', content: 'Welcome to JavaTpoint!!'}, {id: 2, title: 'Second', content: 'It is the best ReactJS Tutorial!!'}, {id: 3, title: 'Third', content: 'Here, you can learn all the ReactJS topics!!'} ]; //array of objects const showdata=data.map((item)=>{ return <option value={item.id}>{item.content}</option>; }); const showlist=data.map((item)=>{ return <li key={item.id}>{item.title}</li>; }); class Keys extends React.Component { render(){ return( <div> <h2>rendering using keys,list,dropdown in dom</h2> <select>{showdata}</select> <br></br><br></br> <ul>{showlist}</ul> <br></br><br></br> <ol>{showlist}</ol> </div> ); } } export default Keys;List.js
import React from 'react' const myList = ['Peter', 'Sachin', 'Kevin', 'Dhoni', 'Alisa','Sourav','Ramesh']; const listItems = myList.map((val)=>{ return <li>{val}</li>; }); const dataitem=myList.map( (val)=>{return <option value={val}>{val}</option>;} ) const tabdata=myList.map( (val)=>{return <tr><td>{val}</td></tr>} ) class List extends React.Component { render(){ return( <div> <h2>Unordered List :</h2> <ul type='square'>{listItems}</ul> <br></br> <h2>Ordered List :</h2> <ol type='i'>{listItems}</ol> <h3>Dropdown List</h3> <select multiple>{dataitem}</select> <h3>Table</h3> <table border='1' bgcolor='lightgreen'> <tr><th>USERNAME</th></tr> {tabdata} </table> </div> ); } } export default List;Formex.js
import React from 'react'; class Formex extends React.Component { state={ uid:'', uid_error:'', pass:'', pass_error:'', loc:'', loc_error:'', age:0, age_error:'', email:'', email_error:'', gender:'', gender_error:'', lang:[], lang_error:'' } handleChange=(e)=>{ let index; if(e.target.name=="lang") { if(e.target.checked) { this.state.lang.push(e.target.value); console.log('push:',this.state.lang); // console.log("state :"+this.state); } else { index=this.state.lang.indexOf(e.target.value); this.state.lang.splice(index,1); console.log('pop:',this.state.lang); } } else { this.setState({[e.target.name]:[e.target.value]}) } } mySubmitHandler=(e)=>{ e.preventDefault(); //to prevent default page loading let count=0 if(this.state.uid =='') { this.setState({uid_error:'user id can not be blank'}) count++ } else{this.setState({uid_error:''}) } if(this.state.pass=='') { this.setState({pass_error:'passowrd can not be empty'}) count++ } else {this.setState({pass_error:''})} if(this.state.loc=='') { this.setState({loc_error:'location can not be empty'}) count++ } else {this.setState({loc_error:''})} if(this.state.age=='') { this.setState({age_error:'age can not be empty'}) count++ } else {this.setState({age_error:''})} if(this.state.email=='') { this.setState({email_error:'email can not be empty'}) count++ } else {this.setState({email_error:''})} if(this.state.gender=='') { this.setState({gender_error:'gender can not be empty'}) count++ } else {this.setState({gender_error:''})} if(this.state.lang=='') { this.setState({lang_error:'language can not be empty'}) count++ } else {this.setState({lang_error:''})} if(count===0) { return true // alert("Form is submitting successfully") } else{ return false } } render() { var myStyle = { fontSize: 20, fontFamily: 'Courier', color: 'red' } return( <div> <form onSubmit={this.mySubmitHandler}> <label style = {myStyle}>USERID :</label> <input type="text" name="uid" onChange={this.handleChange}/> <span>{this.state.uid_error}</span> <br></br><br></br> <label style = {myStyle}>PASSWORD :</label> <input type="password" name="pass" onChange={this.handleChange}/> <span>{this.state.pass_error}</span> <br></br><br></br> <label style = {myStyle}>LOCATION :</label> <select name="loc" onChange={this.handleChange}> <option value="">Select country</option> <option value="india">IND</option> <option value="australia">AUS</option> <option value="sri lanka">SL</option> <option value="china">CH</option> </select> <span>{this.state.loc_error}</span> <br></br><br></br> <label style = {myStyle}>AGE:</label> <input type="number" name="age" onChange={this.handleChange}/> <span>{this.state.age_error}</span> <br></br><br></br> <label style = {myStyle}>EMAIL:</label> <input type="email" name="email" onChange={this.handleChange}/> <span>{this.state.email_error}</span> <br></br><br></br> <label style = {myStyle}>GENDER:</label> <input type="radio" name="gender" value="male" onChange={this.handleChange}/>Male <input type="radio" name="gender" value="female" onChange={this.handleChange}/>Female <span>{this.state.gender_error}</span> <br></br><br></br> <label style = {myStyle}>LANGUAGES:</label> <input type="checkbox" name="lang" value="Bengali" onChange={this.handleChange}/>Beng <input type="checkbox" name="lang" value="Hindi" onChange={this.handleChange}/>Hindi <input type="checkbox" name="lang" value="English" onChange={this.handleChange}/>Eng <span>{this.state.lang_error}</span> <br></br><br></br> <input type="submit" value="Register"/> </form> </div> ); } } export default Formex;------------------------------------------------------------------------------------------------------------------------------------------------------------------Refs Examples , Props concept , ExamplesDimension.jsimport React from 'react'; import Findsi from './Findsi'; export default class Dimension extends React.Component { state={ prin:'', rate:'', time:'', status:false } valChng=(event)=>{ this.setState({[event.target.name]:[event.target.value]}); } find=(event)=>{ this.setState({status:true}); } resetval=(event)=>{ this.setState({status:false}); } render() { return( <> ENTER PRINCIPAL : <input type='number' name='prin' onChange={this.valChng}/> <br></br> ENTER RATE : <input type='number' name='rate' onChange={this.valChng}/> <br></br> ENTER TIME : <input type='number' name='time' onChange={this.valChng}/> <br></br> <button onClick={this.find}>CALC</button> <button onClick={this.resetval}>RESET</button> { (this.state.status===true)? (<Findsi p={this.state.prin} r={this.state.rate} t={this.state.time}/>): (null) } </> ); } }Condrend2.jsimport React from 'react' import AuthButton from './AuthButton' class Condrend2 extends React.Component { constructor(props) { super(props); this.state = { isLoggedIn:'hi' }; } render() { return ( <div> <h1> Props Passing concept in React. </h1> <AuthButton x={this.state.isLoggedIn} /> </div> ); } } export default Condrend2;Refex3.js
import React from "react"; export default class Refex3 extends React.Component { constructor(props) { super(props); this.username = React.createRef(); this.password = React.createRef(); this.state = { errors: [] }; } handleSubmit = (event) => { event.preventDefault(); const username = this.username.current.value; const password = this.password.current.value; const errors = this.handleValidation(username, password); if (errors.length > 0) { this.setState({ errors }); return; } else { this.setState({ errors }); alert("Successful submit done!"); } }; handleValidation = (username, password) => { const errors = []; if (username.length === 0) { errors.push("Username cannot be empty"); } if (password.length < 6) { errors.push("Password should be at least 6 characters long"); } return errors; }; render() { const { errors } = this.state; //object destructuring return ( <div> <h1>React Ref Example</h1> <form onSubmit={this.handleSubmit}> {errors.map(error => <p key={error}>{error}</p>)} <label>Username:</label> <input type="text" ref={this.username} /> <br></br><br></br> <label>Password:</label> <input type="password" ref={this.password} /> <br></br><br></br> <button>Submit</button> </form> </div> ); } }Refex2.jsimport React from "react"; export default class Refex2 extends React.Component { constructor(props) { super(props) // Create the ref this.textInput = React.createRef(); this.state = { value:[] } } // Set the state for the ref handleSubmit = (e) => { e.preventDefault(); this.state.value.push(this.textInput.current.value); this.setState({value:this.state.value}); this.textInput.current.value=""; }; render() { return ( <div> <h1>React Ref - createRef</h1> <ol type="I"> { this.state.value.map((val,index)=>{return <li key={index}>{val}</li>} ) } </ol> <br></br><br></br> <form onSubmit={this.handleSubmit}> ENTER NAME :<input type="text" ref={this.textInput} /> <button>Submit</button> </form> </div> ); } }Findsi.jsimport React from 'react'; export default function Findsi(props) { let si=(props.p*props.r*props.t)/100; let amt=parseInt(si)+parseInt(props.p); return( <h3>SI IS : {si} AMOUNT IS : {amt}</h3> );}---------------------------------------------------------------------------Props concept , Lifecycle Concept ,Examples ,Noteslifecycle.txt
Class component ---- It has a specific lifecycle . It follows the life cycle methods through out its execution. Functional component ---- We do not have any lifecycle methods. Functional component does not have a lifecycle. Class Component ---- it has 4 states : 1. Initialisation state (state 1): it will initialise the state object and the props. constructor()----> it will initialise the state and props. 2. Mounting state / Loading state (state 2): in this state the class component will be loaded . componentWillMount() render()----> this will return from the component componentDidMount() 3. Updating state (state 3): when we will update any state property in my component using setState() then my component will move to the updating state. shouldComponentUpdate() ---> it is a boolean functions which returns true/false if this method will return false then the state update will not be done. componentWillUpdate() render() ----->this is again called here to show the updated state value. componentDidUpdate() 4. Unmounting state / Unloading state (state 4): When my component will be unloaded then it will be in unmounting state. componentWillUnmount()
lifeex1.jsimport React, { Component } from 'react' export default class Lifeex1 extends Component { constructor(props){ super(props) this.state = { name: 'Hello the message will change. Please Wait!' } } componentDidMount() { setTimeout(() => { this.setState({name:'Welcome to Ejobindia kolkata!'}) }, 5000) } componentDidUpdate(prevState){ if(prevState.name !== this.state.name){ document.getElementById('statechange').innerHTML = "Yes the state is changed" } } render() { return ( <div> <h3>Message Display :</h3> {this.state.name} <br></br> <h3 id="statechange">hello</h3> </div> ) } }lifecycle.jsimport React from 'react' class Lifecycle extends React.Component { constructor(props) { super(props); this.state = { hello : "welcome to Kolkata!" }; console.log("constructor is called"); } componentWillMount() { console.log("componentWillMount() is called"); } componentDidMount() { console.log("componentDidMount() is called"); } changeState=(e)=> { this.setState({ hello : "EjobIndia!" }); } render() { return ( <div> <h1>Welcome All, { this.state.hello }</h1> <h2> <button onClick={this.changeState}>Click Here!</button> </h2> </div>); } shouldComponentUpdate() { console.log("shouldComponentUpdate() is called"); return true; } componentWillUpdate() { console.log("componentWillUpdate() is called"); alert("state value will be update soon...."); } componentDidUpdate() { console.log("componentDidUpdate() is called"); alert("State value is updated"); } } export default LifecycleLifeex2.jsimport React, { Component } from 'react' export default class Lifeex2 extends Component { constructor(props){ super(props) this.state = { show: true } } render() { return ( <> <p>{this.state.show ? <Child/> : null}</p> <button onClick={() => {this.setState({show: !this.state.show})}}> Click me to toggle</button> </> ) } } export class Child extends Component{ componentWillUnmount(){ alert('Child will unmount') } render(){ return( <div> <h3>I am a child component</h3> </div> ) } }Condrender.jsimport React from 'react' //functional components // Message Component function Message(props) { if (props.val) return <h1> Welcome Back!!!</h1>; else return <h1>Please Login First!!!</h1>; } // Login Component function Login(props) { return( <button onClick = {props.clickInfo}> Login </button> ); } // Logout Component function Logout(props) { return( <button onClick = {props.clickInfo}> Logout </button> ); } class Condrender extends React.Component { constructor(props) { super(props); //initialisation of props this.state = {isLoggedIn :false}; } handleLogin=()=>{ this.setState({isLoggedIn : true}); } handleLogout=()=>{ this.setState({isLoggedIn : false}); } render() { return( <div> <h1> Conditional Rendering Example </h1> <Message val = {this.state.isLoggedIn}/> { (this.state.isLoggedIn)?( <Logout clickInfo = {this.handleLogout} /> ) : ( <Login clickInfo = {this.handleLogin} /> ) } </div> ); } } export default Condrender;Biodata.jsimport React from 'react'; class Biodata extends React.Component { state={ name:'', age:'', loc:'', gen:'' } componentDidMount() { setTimeout( ()=>{this.setState( {name:'Sourav',age:20,loc:'kolkata',gen:'male'} )}, 5000 ) } componentDidUpdate(prevState){ if(prevState.name !== this.state.name){ document.getElementById('msg').innerHTML = "THANK YOU. GOOD BYE!" } } render() { return( <> <h3>BIODATA</h3> <ul type='circle'> <li>NAME : {this.state.name}</li> <li>AGE : {this.state.age}</li> <li>LOCATION : {this.state.loc}</li> <li>GENDER : {this.state.gen}</li> </ul> <br></br> <p id='msg'>Wait for 5 secs!</p> </> ); } } export default Biodata-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Routing Concept , Examples (PART 1) + (PART 2)App.js
import logo from './logo.svg'; import './App.css'; import Child from './components/Child'; import Parent from './components/Parent'; import Refex2 from './components/Refex2'; import Refex3 from './components/Refex3'; import Table from './components/Table'; import Refsex from './components/Refsex'; import Menu from './routeex/Menu'; import Emp from './routeex/Emp'; import Compnew from './routeex/compnew'; import Users from './routeex/users'; import Student from './routeex/Student'; import Firstex from './routeex/Firstex'; import {NavLink ,Link} from 'react-router-dom'; import Public from './navroute/Public'; import Login from './navroute/Login'; import Home from './navroute/Home'; import Keys from './components/Keys'; import Keys2 from './components/Keys2'; import Dimension from './components/Dimension'; import Condrender from './components/Condrender'; import Lifecycle from './components/Lifecycle'; import Lifeex1 from './components/Lifeex1'; import Lifeex2 from './components/Lifeex2'; import Condrend2 from './components/Condrend2'; //import Refsex from './components/Refsex'; import Biodata from './components/Biodata'; import {Route,BrowserRouter} from 'react-router-dom'; import TodoList from './components/TodoList'; function App() { return ( <> <BrowserRouter> <Route path="/" component={Menu} /> <Route path="/firstex" component={Firstex} /> <Route path="/compnew/:var_loc" component={Compnew}></Route> <Route path="/users" component={Users}></Route> <Route path="/empinfo" component={Emp}></Route> <Route path="/studinfo" component={Student}></Route> </BrowserRouter> {/* <BrowserRouter> <ul> <li> <Link to="/">Public</Link> </li> <li> <NavLink to="/login" activeStyle={{fontWeight:"bold",color:"green",backgroundColor:"pink", fontStyle:"italic"}}> LOGIN </NavLink> </li> <li> <NavLink to="/dashboard" activeStyle={{fontWeight: "bold",color: "red",backgroundColor:"yellow",fontStyle:"italic" }}> DASHBOARD </NavLink> </li> </ul> <Route exact path="/" component={Public}/> <Route path="/login" component={Login} /> <Route path="/dashboard" component={Home} /> </BrowserRouter> */} {/* <Condrender/> */} {/* <Lifecycle/> */} {/* <Lifeex1/> */} {/* <Lifeex2/> */} {/* <Biodata/> */} {/* <Refsex/> */} {/* <Dimension/> */} {/* <Condrend2/> */} {/* <Refex2/> */} {/* <Refex3/> */} {/* <Table/> */} {/* <TodoList/> */} </> ); } export default App;Compnew.jsimport React from 'react' class Compnew extends React.Component { render() { return( <div> <h2 style={{color:'green'}}>USE CASE 2</h2> <label>Prop value is :</label> {this.props.match.params.var_loc} </div> ); } } export default CompnewEmp.jsimport React from 'react' class Emp extends React.Component { state={ p_stid:'', p_stnm:'', p_stloc:'' } componentWillMount() //lifecycle method calls before render() { if(!this.props.location.emp_data) { alert ("No props found!") } else { this.setState( { p_stid:this.props.location.emp_data.u_id, p_stnm:this.props.location.emp_data.u_name, p_stloc:this.props.location.emp_data.u_loc } ) } } render() { return( <div> <h2 style={{color:'green'}}>USE CASE 4</h2> <h1>WELCOME {this.state.p_stid}</h1> <h2>Your Name : {this.state.p_stnm}</h2> <h2>Your location : {this.state.p_stloc}</h2> </div> // <div> // <h1>WELCOME : {this.props.location.emp_data.u_id}</h1> // <h2>Your Name : {this.props.location.emp_data.u_name} </h2> // <h2>Your location : {this.props.location.emp_data.u_loc}</h2> // </div> ); } } export default EmpFirstex.jsimport React from 'react'; class Firstex extends React.Component { componentWillMount() { document.title='USECASE 1'; } componentWillUnmount() { document.title='ReactApp'; alert('Usecase 1 is unloaded!') } render() { return( <div> <h2 style={{color:'green'}}>USE CASE 1</h2> <br></br> <table border="1"> <tr> <th>Fname</th> <th>Lname</th> <th>Age</th> </tr> <tr> <td>Sourav</td> <td>Kundu</td> <td>33</td> </tr> </table> </div> ); } } export default Firstex;Menu.jsimport React from 'react'; import {Link} from 'react-router-dom'; class Menu extends React.Component { state={ id:101, name:'sourav kundu', loc:'kolkata' } render() { const li_style={float:'left',display:'inline-block',backgroundColor:'lightgreen',width:'20%', border:'5px brown double'} return( <> <ul> <li style={li_style}> <Link to="/firstex"><b>UseCase1</b></Link> </li> <li style={li_style}> <Link to={{pathname:'/compnew/'+this.state.name}}><b>UseCase2</b></Link> </li> <li style={li_style}> <Link to={{pathname:'/users/', u_id:this.state.id,u_name:this.state.name,u_loc:this.state.loc}}><b>UseCase3</b></Link> </li> <li style={li_style}> <Link to={{pathname:'/empinfo/', emp_data:{u_id:this.state.id,u_name:this.state.name,u_loc:this.state.loc}}}><b>UseCase4</b></Link> </li> <li style={li_style}> <Link to={{pathname:'/studinfo/', stud_data:{st_id:this.state.id,st_name:this.state.name,st_loc:this.state.loc}}}><b>UseCase5</b></Link> </li> </ul> </> ); } } export default Menu;Student.jsimport React from 'react' class Student extends React.Component { state={ p_stid:'', p_stnm:'', p_stloc:'' } componentDidMount() //lifecycle method calls after render() { console.log('componentdidmount is called'); if(!this.props.location.stud_data) { alert("No props found!") } else { this.setState( { p_stid:this.props.location.stud_data.st_id, p_stnm:this.props.location.stud_data.st_name, p_stloc:this.props.location.stud_data.st_loc } ) } } componentDidUpdate(prevState) { console.log('componentdidupdate is called'); if(prevState.p_stid===this.state.p_stid) { alert('No state is updated') } else { alert('State update is done') } } render() { return( <div> <h2 style={{color:'green'}}>USE CASE 5</h2> <h1>WELCOME {this.state.p_stid}</h1> <h2>Your Name : {this.state.p_stnm}</h2> <h2>Your location : {this.state.p_stloc}</h2> </div> ); } } export default Studentusers.jsimport React from 'react' class Users extends React.Component { render() { return( <div> <h2 style={{color:'green'}}>USE CASE 3</h2> <h1>WELCOME {this.props.location.u_id}</h1> <h2>Your Name : {this.props.location.u_name}</h2> <h2>Your location : {this.props.location.u_loc}</h2> </div> ); } } export default Users------------------------------------------------------------------------------------------------------------------------------------------------------------------------NavLink Concept , Example , HOC concept , ExamplesHome.js
import React from "react"; //import "./styles.css"; export default function Login(props) { const login = () => { props.history.push("/dashboard"); }; return ( <div> <h1>Login Page</h1> <br /> <button onClick={login}>Login</button> </div> ); }Login.jsimport React from "react"; //import "./styles.css"; export default function Public(props) { return ( <> <h1>Public Page</h1> <p>Thank you!</p> </> ); }public.jsimport logo from './logo.svg'; import './App.css'; import Child from './components/Child'; import Parent from './components/Parent'; import Refex2 from './components/Refex2'; import Refex3 from './components/Refex3'; import Table from './components/Table'; import Refsex from './components/Refsex'; import Menu from './routeex/Menu'; import Emp from './routeex/Emp'; import Compnew from './routeex/compnew'; import Users from './routeex/users'; import Student from './routeex/Student'; import Firstex from './routeex/Firstex'; import {NavLink ,Link} from 'react-router-dom'; import Public from './navroute/Public'; import Login from './navroute/Login'; import Home from './navroute/Home'; import Keys from './components/Keys'; import Keys2 from './components/Keys2'; import Dimension from './components/Dimension'; import Condrender from './components/Condrender'; import Lifecycle from './components/Lifecycle'; import Lifeex1 from './components/Lifeex1'; import Lifeex2 from './components/Lifeex2'; import Condrend2 from './components/Condrend2'; //import Refsex from './components/Refsex'; import Biodata from './components/Biodata'; import {Route,BrowserRouter} from 'react-router-dom'; import TodoList from './components/TodoList'; function App() { return ( <> {/* <BrowserRouter> <Route path="/" component={Menu} /> <Route path="/firstex" component={Firstex} /> <Route path="/compnew/:var_loc" component={Compnew}></Route> <Route path="/users" component={Users}></Route> <Route path="/empinfo" component={Emp}></Route> <Route path="/studinfo" component={Student}></Route> </BrowserRouter> */} <BrowserRouter> <ul> <li> <Link to="/">Public</Link> </li> <li> <NavLink to="/login" activeStyle={{fontWeight:"bold",color:"green",backgroundColor:"pink", fontStyle:"italic"}}> LOGIN </NavLink> </li> <li> <NavLink to="/dashboard" activeStyle={{fontWeight: "bold",color: "red",backgroundColor:"yellow",fontStyle:"italic" }}> DASHBOARD </NavLink> </li> </ul> <Route exact path="/" component={Public}/> <Route path="/login" component={Login} /> <Route path="/dashboard" component={Home} /> </BrowserRouter> {/* <Condrender/> */} {/* <Lifecycle/> */} {/* <Lifeex1/> */} {/* <Lifeex2/> */} {/* <Biodata/> */} {/* <Refsex/> */} {/* <Dimension/> */} {/* <Condrend2/> */} {/* <Refex2/> */} {/* <Refex3/> */} {/* <Table/> */} {/* <TodoList/> */} </> ); } export default App;app.jsimport logo from './logo.svg'; import './App.css'; import Child from './components/Child'; import Parent from './components/Parent'; import Refex2 from './components/Refex2'; import Refex3 from './components/Refex3'; import Table from './components/Table'; import Refsex from './components/Refsex'; import Menu from './routeex/Menu'; import Emp from './routeex/Emp'; import Compnew from './routeex/compnew'; import Users from './routeex/users'; import Student from './routeex/Student'; import Firstex from './routeex/Firstex'; import {NavLink ,Link} from 'react-router-dom'; import Public from './navroute/Public'; import Login from './navroute/Login'; import Home from './navroute/Home'; import Keys from './components/Keys'; import Keys2 from './components/Keys2'; import Dimension from './components/Dimension'; import Condrender from './components/Condrender'; import Lifecycle from './components/Lifecycle'; import Lifeex1 from './components/Lifeex1'; import Lifeex2 from './components/Lifeex2'; import Condrend2 from './components/Condrend2'; //import Refsex from './components/Refsex'; import Biodata from './components/Biodata'; import {Route,BrowserRouter} from 'react-router-dom'; import TodoList from './components/TodoList'; function App() { return ( <> {/* <BrowserRouter> <Route path="/" component={Menu} /> <Route path="/firstex" component={Firstex} /> <Route path="/compnew/:var_loc" component={Compnew}></Route> <Route path="/users" component={Users}></Route> <Route path="/empinfo" component={Emp}></Route> <Route path="/studinfo" component={Student}></Route> </BrowserRouter> */} <BrowserRouter> <ul> <li> <Link to="/">Public</Link> </li> <li> <NavLink to="/login" activeStyle={{fontWeight:"bold",color:"green",backgroundColor:"pink", fontStyle:"italic"}}> LOGIN </NavLink> </li> <li> <NavLink to="/dashboard" activeStyle={{fontWeight: "bold",color: "red",backgroundColor:"yellow",fontStyle:"italic" }}> DASHBOARD </NavLink> </li> </ul> <Route exact path="/" component={Public}/> <Route path="/login" component={Login} /> <Route path="/dashboard" component={Home} /> </BrowserRouter> {/* <Condrender/> */} {/* <Lifecycle/> */} {/* <Lifeex1/> */} {/* <Lifeex2/> */} {/* <Biodata/> */} {/* <Refsex/> */} {/* <Dimension/> */} {/* <Condrend2/> */} {/* <Refex2/> */} {/* <Refex3/> */} {/* <Table/> */} {/* <TodoList/> */} </> ); } export default App;HOC_exABOUT.JS
import React from 'react';import "./styles.css";import withHeader from './withHeader';function About(props){return(<div className="App"><h3>{props.title}</h3><p>{props.para}</p></div>)}export default withHeader(About);
DASHBOARD.JS
import "./styles.css";import withHeader from "./withHeader";function Dashboard(props) {return (<div className="App"><h4>{props.title}</h4><hr/><p>In publishing and graphic design, Lorem ipsum is a placeholder textcommonly used to demonstrate the visual form of a document or a typefacewithout relying on meaningful content.</p></div>);}export default withHeader(Dashboard);//export default Dashboard
FOOTER.JS
import React from 'react'export default function Footer(){return (<div className="App footer"><h1>THANK YOU!</h1><h2>VISIT AGAIN!</h2><hr/></div>);}
HEADER.JS
.App {font-family: sans-serif;text-align: center;}.header{height:100px;background-color:dodgerblue;}.footer{height:100px;background-color:lightgreen;}STYLE.CSS
import React from "react";import Header from "./Header";import Footer from "./Footer";/* HOC component*/export default function withHeader(Component) {function NewComponent(props) {return (<><Header/><Component {...props}/><Footer/></>);}return NewComponent;}
WITHhEADER.JS
import React from "react";import Header from "./Header";import Footer from "./Footer";/* HOC component*/export default function withHeader(Component) {function NewComponent(props) {return (<><Header/><Component {...props}/><Footer/></>);}return NewComponent;}HOC_EX2COMMENTScOUNT.JS
import React, { Component } from "react";import HOC from "./HOC";class CommentsCount extends Component {render() {return (<div>Total Comments : {this.props.CountNumber} <br /><button onClick={this.props.handleCLick}>Add Comment!</button></div>);}}const EnhancedComments = HOC(CommentsCount, 5);export default EnhancedComments;
HOC.JS
import React, { Component } from "react";const HOC = (Component, data) => {//console.log("data", data);return class extends React.Component {constructor(props) {super(props);this.state = {count: data,};}handleClick = () => {this.setState({count: this.state.count + 1,});};render() {return (<ComponentCountNumber={this.state.count}handleCLick={this.handleClick}/>);}};};export default HOC;
LIKEScOUNT.JS
import React, { Component } from "react";import HOC from "./HOC";class LikesCount extends Component {render() {return (<div>{this.props.CountNumber} <br /><button onClick={this.props.handleCLick}>Like👍🏻</button></div>);}}const EnhancedLikes = HOC(LikesCount, 10);export default EnhancedLikes;
------------------------v------------------------------------------------------------------------------------------------------------------------------
HOOKS concept , Examples (PART 1)NOTEX.TXTimport { useRef, useState } from 'react'; export default function Stopwatch() { const timerIdRef = useRef(0); const [count, setCount] = useState(0); const startHandler = () => { if (timerIdRef.current==null) { return; } timerIdRef.current = setInterval(() => setCount(count => count+1), 1000); }; const stopHandler = () => { clearInterval(timerIdRef.current); timerIdRef.current = 0; }; return ( <div> <div>Timer: {count}s</div> <div> <button onClick={startHandler}>Start</button> <button onClick={stopHandler}>Stop</button> </div> </div> ); }sTOPwATCH.JSimport { useRef, useState } from 'react'; export default function Stopwatch() { const timerIdRef = useRef(0); const [count, setCount] = useState(0); const startHandler = () => { if (timerIdRef.current==null) { return; } timerIdRef.current = setInterval(() => setCount(count => count+1), 1000); }; const stopHandler = () => { clearInterval(timerIdRef.current); timerIdRef.current = 0; }; return ( <div> <div>Timer: {count}s</div> <div> <button onClick={startHandler}>Start</button> <button onClick={stopHandler}>Stop</button> </div> </div> ); }
InputFocus.js
import React, {useState, useEffect} from 'react'; function Hookseg2() { //Define State const [name, setName] = useState({firstName: 'Sourav', surname: 'kundu'}); const [title, setTitle] = useState('BIOLOGY'); //Call the use effect hook // pass in an empty array as a second argument useEffect(() => { const timer = setInterval(() => { setName({firstName: 'Shedrack', surname: 'Akintayo'}) setTitle('Test React Js') }, 5000); // clearing interval return () => clearInterval(timer); },[]); return( <div> <h1>Title: {title}</h1> <h3>Name: {name.firstName}</h3> <h3>Surname: {name.surname}</h3> </div> ); }; export default Hookseg2
Hookseg2.jsimport React, {useState, useEffect} from 'react'; function Hookseg2() { //Define State const [name, setName] = useState({firstName: 'Sourav', surname: 'kundu'}); const [title, setTitle] = useState('BIOLOGY'); //Call the use effect hook // pass in an empty array as a second argument useEffect(() => { const timer = setInterval(() => { setName({firstName: 'Shedrack', surname: 'Akintayo'}) setTitle('Test React Js') }, 5000); // clearing interval return () => clearInterval(timer); },[]); return( <div> <h1>Title: {title}</h1> <h3>Name: {name.firstName}</h3> <h3>Surname: {name.surname}</h3> </div> ); }; export default Hookseg2Hookseg1.jsimport React, {useState} from 'react'; function Hookseg1() { const [age, setAge] = useState('20'); const [loc,setLoc]=useState('Patna'); const [name,setName]=useState('Avishek'); const valueChange=(e)=>{ if(e.target.name==="name") { setName(e.target.value); } else if(e.target.name==="age") { setAge(e.target.value); } else if(e.target.name==="loc") { setLoc(e.target.value); } }; return ( <> <h3>I am {age} Years Old . My name is {name} . I stay in {loc}</h3> Enter name : <input type="text" name="name" onChange={valueChange}/> <br></br> Enter age : <input type="number" name="age" onChange={valueChange}/> <br></br> Enter Loc : <input type="text" name="loc" onChange={valueChange}/> <br></br> </> ); } export default Hookseg1------------------------v------------------------------------------------------------------------------------------------------------------------------Hooks Examples (PART 2)hookex4.jsimport React from "react"; //The React useMemo Hook returns a memoized value. //The useMemoHook accepts a second parameter to declare dependencies. The function will only run when its dependencies have changed. import { useState,useMemo } from "react"; export default function Hookex4(props) { const [count, setCount] = useState(0); const [todos, setTodos] = useState([]); const calculation = useMemo(() => expensiveCalculation(count), [count]); //const calculation = expensiveCalculation(count); //direct calling const increment = () => { setCount((count) => count + 1); }; const addTodo = () => { setTodos((todos) => [...todos, "New Task added"]); }; return ( <div> <div> <h2>My Todos</h2> {todos.map((todo, index) => { return <p key={index}>{todo}</p>; })} <button onClick={addTodo}>Add Todo</button> </div> <hr /> <div> Count: {count} <button onClick={increment}>+</button> <h2>Expensive Calculation</h2> {calculation} </div> </div> ); } const expensiveCalculation = (num) => { console.log("Calculating..."); for (let i = 0; i < 100; i++) { num++; } return num; };logbuttonclicks.jsimport { useRef, useState } from "react"; export default function LogButtonClicks() { const countRef = useRef(10); const[hit,setHit]=useState(''); const handle = () => { countRef.current++; console.log(`Clicked ${countRef.current} times`); setHit(countRef.current); }; console.log("I rendered!"); return( <> <button onClick={handle}>Click me</button> <br></br> <h3>Page Hits Occurs {hit} times</h3> </> ); }Hooksex3.jsimport {useState,useEffect} from 'react'; const Hooksex3 = () => { const [count, setCount] = useState(0) useEffect(() => { document.title = `You clicked ${count} times` },[count]) // Only re-run the effect if count changes return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}>Click me</button> </div> ) } export default Hooksex3stateobject.jsimport React from 'react'; import { useState } from 'react'; const StateObject = () => { const [state, setState] = useState({ age: 19, siblingsNum: 4 }) const handleClick = (val,e) =>{ setState({ ...state, [val]: state[val] + 1 }) } const handleClick2 = (val,e) =>{ setState({ ...state, [val]: state[val] + 2 }) } const { age, siblingsNum } = state //destructuring of object return ( <div> <p>Today I am {age} Years of Age</p> <p>I have {siblingsNum} siblings</p> <div> <button onClick={handleClick.bind(null,'age')}>Get older!</button> <button onClick={handleClick2.bind(null, 'siblingsNum')}> More siblings! </button> </div> </div> ) } export default StateObjectCountMyRenders.jsimport React, { useState, useEffect } from 'react'; export default function CountMyRenders() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title using the browser API document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }--------------------------------------------------------------------------------------------------------------------------------API access using React , axios.get() , concept , Examplesapi_notes_extra.txtAlert : React module : sweetalert module E:\React_Work>cd firstapp E:\React_Work\firstapp>npm install sweetalert import swal from 'sweetalert'; syntax: swal(msg_status,msg_text,alert_type); msg_status "Login success" msg_text "Login is seccessful" alert_type : "success" , "failure" , "error" routing using button : log=(e)=>{ this.props.history.push('/login') } <input type='button' value='Login' onClick={this.log} /> <BrowserRouter> <Route path="/login" component={Login}/> </BrowserRouter> Redirect concept : redirect --- routing --- forceful import {Redirect} from 'react-router-dom'; syntax : <Redirect to="/path"/> localstorage concept : it is a temporary storage area within the browser Go to inspect ---> Application ---> Storage ---> localStorage javascript ---- localstorage pre defined object / implicit object setItem("key","value") // this function will create a key value pair in the localstorage getItem("key") // this function will provide the value for the specific key if the key exsisit. if the key does not exsist it will return flase. removeItem("key") // this function will remove the key value pair from the localStorage permanently. Login ----> useid : pwd : useiid ----> localStorage temp store Logout ----> remove the userid localstorageapi_concept
Apisex2.jsimport React from 'react'; import axios from 'axios'; export default function Apiex2() { const datafetch=(e)=>{ axios.get('https://jsonplaceholder.typicode.com/posts/1') .then( (res)=>{console.log(res.data); console.log("userID :"+res.data.userId); console.log("ID :"+res.data.id); console.log("TITTLE :"+res.data.title); console.log("BODY :"+res.data.body); } ) .catch( (err)=>{console.log("ERROR MSG :",err);} ) .finally( ()=>{console.log("API CALL IS OVER!");} ) } return( <> <h3>API EXAMPLE</h3> <input type='button' value='TEST' onClick={datafetch} /> </> ) }Apitest.jsimport React from 'react' import axios from 'axios' import {useState} from 'react' const Apitest=(props)=>{ const[uid,setUid]=useState(''); const[body,setBody]=useState(''); const apidata=()=>{ axios.get('https://jsonplaceholder.typicode.com/posts/1') .then( (res)=>{ //console.log("response",res.data); //console.log("USERID :",res.data.userId); //console.log("Body :",res.data.body) setUid(res.data.userId); setBody(res.data.body); } ) .catch( (err)=>{console.log("ERROR :",err);} ) .finally( ()=>{console.log("API CALL IS OVER!")} ) } return( <> <ul> <li>USERID : {uid}</li> <li>BODY : {body}</li> </ul> <input type='button' value='SHOW' onClick={apidata}/> </> ) } export default Apitest----------------------------------------------------------------------------------------------------------------Api data render using map() , Data render using Table , List from Api , axios.post()Apiex.jsimport React from 'react'; import axios from 'axios'; import { useState } from 'react'; export default function Apiex2() { const [item,setItem]=useState({}); const viewdata=(event)=>{ axios.get('https://reqres.in/api/users/2') .then( (res)=>{ console.log(res.data); console.log("result :",res.data.data); setItem(res.data.data); } ) .catch( (err)=>{ console.log("ERROR :"+err); } ) } return( <> <button onClick={viewdata}>SHOW</button> <ul> <li>{item.id}</li> <li>{item.email}</li> <li>{item.first_name}</li> <li><img src={item.avatar} alt='sorry'/></li> </ul> </> ); }Apiex2.jsimport React from 'react'; import axios from 'axios'; import { useState } from 'react'; export default function Apiex2() { const [item,setItem]=useState({}); const viewdata=(event)=>{ axios.get('https://reqres.in/api/users/2') .then( (res)=>{ console.log(res.data); console.log("result :",res.data.data); setItem(res.data.data); } ) .catch( (err)=>{ console.log("ERROR :"+err); } ) } return( <> <button onClick={viewdata}>SHOW</button> <ul> <li>{item.id}</li> <li>{item.email}</li> <li>{item.first_name}</li> <li><img src={item.avatar} alt='sorry'/></li> </ul> </> ); }PersonData.jsimport React from 'react'; import axios from 'axios'; class PersonData extends React.Component { state={ persons:[] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { const persons = res.data; this.setState({ persons }); }) .catch( err=>{ console.log('error :'+err); }) .finally( ()=>{console.log('API CALL IS OVER!')} ) } render() { return ( <div> <h3>PERSON DATA :</h3> { this.state.persons.map((item,index)=>{ return <ul type='square'> <li key={index+1}>{item.id}</li> <li key={index+2}>{item.username}</li> <li key={index+3}>{item.email}</li> <li key={index+4}>{item.address.street}</li> <li key={index+5}>{item.address.city}</li> <li key={index+6}>{item.address.geo.lat}</li> <li key={index+7}>{item.website}</li> <li key={index+8}>{item.company.name}</li> </ul> } ) } </div> ); } } export default PersonDataapiData.jsimport React from 'react';import axios from 'axios'; class Apidata extends React.Component { state={ id:'', userid:'', title:'', body:'' } disp=(event)=>{ axios.get('https://jsonplaceholder.typicode.com/posts/1') .then( (res)=>{ console.log(res.data) this.setState( { id:res.data.id, userid:res.data.userId, title:res.data.title, body:res.data.body } ) } ) .catch( (err)=>{ console.log("ERROR :"+err) } ) } render() { return( <div> <input type='button' value='SHOW' onClick={this.disp}/> <br></br> <ol> <li>ID:{this.state.id}</li> <li>USERID:{this.state.userid}</li> <li>TITLE:{this.state.title}</li> <li>BODY:{this.state.body}</li> </ol> </div> ); } } export default Apidatapersonlist.jsimport React from 'react'; import axios from 'axios'; export default class PersonList extends React.Component { state = { persons: [] } componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/users`) .then(res => { // console.log('response :'+res.data); const persons = res.data; this.setState({ persons }); }) .catch( err=>{ console.log('error :'+err); }) .finally( ()=>{console.log('API CALLIS OVER!');} ) } render() { return ( <div> <table border='1' width='80%' bgcolor='lightpink'> <tr> <th>USERID</th> <th>USERNAME</th> <th>EMAIL</th> <th>CITY</th> <th>LAT LONG</th> <th>COMPANY</th> </tr> { this.state.persons.slice(0,5).map( (item)=>{ return( <tr> <td>{item.id}</td> <td>{item.username}</td> <td>{item.email}</td> <td>{item.address.city}</td> <td>{item.address.geo.lat}{item.address.geo.lng}</td> <td>{item.company.name}</td> </tr> ) } ) } </table> <br></br> <h3>Dynamic Dropdown List</h3> <select> <option value=''>Select any city</option> { this.state.persons.map((item)=>{ return <option value={item.id}>{item.address.city}</option> } ) } </select> </div> ); } }apipost.jsimport React from 'react'; import axios from 'axios'; export default class Apipost extends React.Component { state={ name:'', job:'', id:'', createat:'' } valchng=(e)=>{ this.setState({[e.target.name]:[e.target.value]}); } apicall=(e)=>{ axios.post('https://reqres.in/api/users',{"name":this.state.name, "job":this.state.job}) .then( (res)=>{ console.log("RESPONSE:",res.data) this.setState({ id:res.data.id, createat:res.data.createdAt }) } ) .catch( (err)=>{console.log('ERROR :',err)} ) } render() { return( <> NAME : <input type="text" name="name" onChange={this.valchng}/> <br></br><br></br> JOB : <input type="text" name="job" onChange={this.valchng}/> <br></br><br></br> <input type="button" value="INSERT" onClick={this.apicall}/> <br></br><br></br> <h3>ID : {this.state.id}</h3> <h3>CREATED AT : {this.state.createat}</h3> </> ) } }----------------------------------------------------------------------------------------export default LoginLocalstorage , Redirect , Sweetalert , props.history.push() concept examplesdashboard.jsimport React from 'react'; import axios from 'axios'; import {Redirect} from 'react-router'; class Dashboard extends React.Component { state={ user_data:[], loading:false } componentDidMount(){ this.setState({loading:true},()=>{ axios.get('https://reqres.in/api/users/2') .then((res)=>{ this.setState({user_data:[res.data.data],loading:false}) //console.log('data',res); }).catch(err=>{ console.log(err); }) }) } render(){ if(!localStorage.getItem('user_id') || localStorage.getItem('user_id')===undefined) {return <Redirect to='/login'></Redirect>} return( this.state.user_data.map((item)=>{ return( <> <label>USERID :</label> <p>{item.id}</p> <br></br> <label>FIRST NAME :</label> <p>{item.first_name}</p> <br></br> <label>LAST NAME :</label> <p>{item.last_name}</p> <br></br> <label>EMAIL :</label> <p>{item.email}</p> <br></br> <label>PROFILE IMAGE :</label> <p><img src={item.avatar} height='100' width='100' alt='sorry unable to load'/></p> <br></br> </> ); }) ); } } export default Dashboardlogin.jsimport React from 'react'; import axios from 'axios'; import swal from 'sweetalert'; class Register extends React.Component { state={ email:'', password:'' } handleChange=(e)=>{ this.setState({[e.target.name]:[e.target.value]}); } handleSubmit=(e)=>{ e.preventDefault(); axios.post('https://reqres.in/api/users',{name:this.state.email,job:this.state.password}) .then(response=>{ swal('Success!','Registration Successful','success'); //showing sweet alert console.log('res:',response.data); localStorage.setItem('user_id',response.data.id); //working like session or cookies this.props.history.push('/login'); // working like action in html form }) .catch(err=>{ swal('Sorry Failed!','Registration Failed','error'); console.log(err) }) } render(){ return( <> <h3>Please Register Here</h3> <form> USERNAME : <input type="text" name="email" onChange={this.handleChange}/> <br></br><br></br> PASSWORD : <input type="password" name="password" onChange={this.handleChange}/> <br></br><br></br> <input type="submit" name="btnsub" value="REGISTER" onClick={this.handleSubmit}/> </form> </> ); } } export default RegisterRegister.jsimport React from 'react'; import axios from 'axios'; import swal from 'sweetalert'; class Register extends React.Component { state={ email:'', password:'' } handleChange=(e)=>{ this.setState({[e.target.name]:[e.target.value]}); } handleSubmit=(e)=>{ e.preventDefault(); axios.post('https://reqres.in/api/users',{name:this.state.email,job:this.state.password}) .then(response=>{ swal('Success!','Registration Successful','success'); //showing sweet alert console.log('res:',response.data); localStorage.setItem('user_id',response.data.id); //working like session or cookies this.props.history.push('/login'); // working like action in html form }) .catch(err=>{ swal('Sorry Failed!','Registration Failed','error'); console.log(err) }) } render(){ return( <> <h3>Please Register Here</h3> <form> USERNAME : <input type="text" name="email" onChange={this.handleChange}/> <br></br><br></br> PASSWORD : <input type="password" name="password" onChange={this.handleChange}/> <br></br><br></br> <input type="submit" name="btnsub" value="REGISTER" onClick={this.handleSubmit}/> </form> </> ); } } export default RegisterApp.jsimport logo from './logo.svg'; //import './App.css'; import Firstex from './components/Firstex'; import Secondex from './components/Secondex'; import Reactstate from './components/Reactstate'; import Formex from './components/Formex'; import Users from './components/users'; import Compnew from './components/compnew'; import Emp from './components/Emp'; import { Route,BrowserRouter} from 'react-router-dom'; import Menu from './components/Menu'; import Student from './components/Student'; import Funccomp from './components/Funccomp'; import Condrender from './components/Condrender'; import Condrend2 from './components/Condrend2'; import Fragment from './components/Fragment'; import List from './components/List'; import Keys from './components/Keys'; import Refsex from './components/Refsex'; import Lifecycle from './components/Lifecycle'; import Home from './components/Home'; import PersonList from './components/PersonList'; import Personadd from './components/Personadd'; import Deleteuser from './components/Deleteuser'; import Specificuser from './components/Specificuser'; import DemoAPI from './components/DemoAPI'; import Hookseg1 from './components/Hookseg1'; import Hookseg2 from './components/Hookseg2'; import Register from './components/Register'; import Login from './components/Login'; import Dashboard from './components/Dashboard'; import Test1 from './api_test/Test1'; import Test2 from './api_test/Test2'; import Test3 from './api_test/Test3'; import Test4 from './api_test/Test4'; import Weather from './api_test/Weather'; import PersonData from './components/PersonData'; import InputFocus from './components/InputFocus'; import LogButtonClicks from './components/LogButtonClicks'; import CountMyRenders from './components/CountMyRenders'; import Form1 from './components/Form1'; import Form2 from './components/Form2'; import Form3 from './components/Form3'; import Form4 from './components/Form4'; import Formtest from './components/Formtest'; import Apiex from './components/Apiex'; import Table from './components/Table'; import Listing from './components/Listing'; import Apidemo from './components/Apidemo'; import Apiex2 from './components/Apiex2'; import Apidata from './components/Apidata'; import Dimension from './components/Dimension'; import StateObject from './components/StateObject'; import Stopwatch from './components/Stopwatch'; import Testapi from './components/Testapi'; import FunctionComp2 from './components/FunctionComp2'; import Apipost from './components/Apipost'; import TodoList from './components/TodoList'; import Apires from './components/Apires'; import Hooksex3 from './components/Hooksex3'; import Hookex4 from './components/Hookex4'; import Apitest from './axios_ex/Apitest'; import Apisex2 from './axios_ex/Apisex2'; function App() { return ( <div className="App"> {/* <BrowserRouter> <div> <Route path="/" component={Menu} /> <Route path="/Firstex" component={Firstex} /> <Route path="/first" component={Home} /> <Route path="/compnew/:var_loc" component={Compnew}></Route> <Route path="/users" component={Users}></Route> <Route path="/empinfo" component={Emp}></Route> <Route path="/studinfo" component={Student}></Route> </div> </BrowserRouter> */} <BrowserRouter> <Route path="/login" component={Login}></Route> <Route exact path="/" component={Register}></Route> <Route path="/showdata" component={Dashboard}></Route> </BrowserRouter> {/* <Lifecycle></Lifecycle> */} {/* <Personadd></Personadd> */} {/* <Refsex></Refsex> */} {/* <Hookseg1></Hookseg1> */} {/* <Hooksex3/> */} {/* <StateObject/> */} {/* <Hookseg2></Hookseg2> */} {/* <InputFocus/> */} {/* <Apiex2/> */} {/* <Apires/> */} {/* <Test2/> */} {/* <Form4/> */} {/* <Lifecycle/> */} {/* <PersonList/> */} {/* <Apipost/> */} {/* <PersonData/> */} {/* <Weather/> */} {/* <Condrender/> */} {/* <Dimension/> */} {/* <Keys/> */} {/* <Refsex/> */} {/* <Lifecycle/> */} {/* <Condrend2/> */} {/* <Formtest/> */} {/* <LogButtonClicks/> */} {/* <Stopwatch/> */} {/* <CountMyRenders/> */} {/* <DemoAPI/> */} {/* <Apiex/> */} {/* <Testapi/> */} {/* <Condrender/> */} {/* <Formex/> */} {/* <Keys/> */} {/* <List/> */} {/* <Table/> */} {/* <Listing/> */} {/* <Apiex/> */} {/* <Apiex2/> */} {/* <FunctionComp2/> */} {/* <PersonList/> */} {/* <TodoList/> */} {/* <Hookex4/> */} {/* <Apidemo/> */} {/* <Apidata/> */} {/* <Apitest/> */} {/* <Apisex2/> */} </div> ); } export default App;api_notes_extra.jsAlert : React module : sweetalert module E:\React_Work>cd firstapp E:\React_Work\firstapp>npm install sweetalert import swal from 'sweetalert'; syntax: swal(msg_status,msg_text,alert_type); msg_status "Login success" msg_text "Login is seccessful" alert_type : "success" , "failure" , "error" routing using button : log=(e)=>{ this.props.history.push('/login') } <input type='button' value='Login' onClick={this.log} /> <BrowserRouter> <Route path="/login" component={Login}/> </BrowserRouter> Redirect concept : redirect --- routing --- forceful import {Redirect} from 'react-router-dom'; syntax : <Redirect to="/path"/> localstorage concept : it is a temporary storage area within the browser Go to inspect ---> Application ---> Storage ---> localStorage javascript ---- localstorage pre defined object / implicit object setItem("key","value") // this function will create a key value pair in the localstorage getItem("key") // this function will provide the value for the specific key if the key exsisit. if the key does not exsist it will return flase. removeItem("key") // this function will remove the key value pair from the localStorage permanently. Login ----> useid : pwd : useiid ----> localStorage temp store Logout ----> remove the userid localstorageNested Routing Concept , Example------------------------------------------------PROJECT PLAN , INTERVIEW QUESTIONS ,fetch api conceptgetrequest.jsimport React from 'react'; class GetRequest extends React.Component { constructor(props) { super(props); this.state = { totalReactPackages: null }; } componentDidMount() { // Simple GET request using fetch fetch('https://api.npms.io/v2/search?q=react') .then(response => response.json()) .then(data => this.setState({ totalReactPackages: data.total },()=>{console.log(data.results[0])})); } render() { const { totalReactPackages } = this.state; return ( <div className="card text-center m-3"> <h5 className="card-header">Simple GET Request</h5> <div className="card-body"> Total react packages: {totalReactPackages} </div> </div> ); } } export default GetRequestGetRequestAsyncAwait.jsimport React from 'react'; class GetRequestAsyncAwait extends React.Component { constructor(props) { super(props); this.state = { totalReactPackages: null }; } async componentDidMount() { // GET request using fetch with async/await const response = await fetch('https://api.npms.io/v2/search?q=react'); const data = await response.json(); this.setState({ totalReactPackages: data.total }) } render() { const { totalReactPackages } = this.state; return ( <div className="card text-center m-3"> <h5 className="card-header">GET Request with Async/Await</h5> <div className="card-body"> Total react packages: {totalReactPackages} </div> </div> ); } } export default GetRequestAsyncAwaitGetRequestErrorHandling.jsimport React from 'react'; class GetRequestErrorHandling extends React.Component { constructor(props) { super(props); this.state = { totalReactPackages: null, errorMessage: null }; } componentDidMount() { // GET request using fetch with error handling //fetch('https://api.npms.io/v2/invalid-url') fetch('https://api.npms.io/v2/search?q=react') .then(async (response) => { const data = await response.json(); // check for error response //fetch provides a simple ok flag that indicates whether an HTTP response’s status code is in the successful range or not if (!response.ok) { // get error message from body or default to response statusText const error = (data.message) || response.statusText; return Promise.reject(error); } this.setState({ totalReactPackages: data.total }) }) .catch((error) => { this.setState({ errorMessage: error.toString() }); console.error('There was an error!', error); }); } render() { const { errorMessage,totalReactPackages } = this.state; return ( <div className="card text-center m-3"> <h5 className="card-header">GET Request with Error Handling</h5> <div className="card-body"> Error message: {errorMessage} <br></br> RESULT: {totalReactPackages} </div> </div> ); } } export default GetRequestErrorHandlingGetRequestHooks.jsimport React, { useState, useEffect } from 'react'; function GetRequestHooks() { const [totalReactPackages, setTotalReactPackages] = useState(null); useEffect(() => { // GET request using fetch inside useEffect React hook fetch('https://api.npms.io/v2/search?q=react') .then(response => response.json()) .then(data => setTotalReactPackages(data.total)); // empty dependency array means this effect will only run once (like componentDidMount in classes) }, []); return ( <div className="card text-center m-3"> <h5 className="card-header">GET Request with React Hooks</h5> <div className="card-body"> Total react packages: {totalReactPackages} </div> </div> ); } export default GetRequestHooksREACT JS QUESTIONS:REACT JS INTERVIEW QUESTIONS : ---------------------------- 1. What is JSX? 2. What is a component in react ? 3. Difference between class components and function components? 4. What is the virtual DOM? 5. How do you create a React app? 6. What is the use of render() in React? 7. How routing is done in react components? 8. How do you update the state of a component? 9. Explain lifecycle methods in react class component. 10.What is axios ?Why it is used? 11.Why props are used? 12.Difference between state and props. 13.How do you pass props between components? 14.What is Redux? 15.What are the components of Redux? 16.What do you understand by refs in React? 17.How is React Router different from Conventional Routing? 18.What is Virtual DOM? 19.What are controlled components? 20.What are uncontrolled components? 21.What is the difference between createElement and cloneElement? 22.What is Lifting State Up in React? 23.What are the different phases of component lifecycle? 24.What are the lifecycle methods of React? 25.What are Higher-Order components? 26.How to create props proxy for HOC component? 27.What is the lifecycle methods order in mounting? 28.How to pass params to history.push method in React Router v4? 29.What is the difference between mapStateToProps() and mapDispatchToProps()? 30.What is an action in Redux?
Comments
Post a Comment