You are reading the article How Variables Work In Lua With Examples? updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How Variables Work In Lua With Examples?
Definition of Lua VariablesThe Lua variable is placing the name to a memory location and store the data of the application. The Lua variable is giving the label to the storage position and helps to manipulate the storage data. The Lua variable helps to refere the memory location to contain the letters, digits, and symbols as information. The Lua variable works as a container to store the information and avoid multiple times use of single information. The Lua variable is the name to store the data with a specific name and use for entire Lua coding as a reference.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax
The Lua variable has three types according to the use, scope, and priority of the variable.
1. The global variable:
Variable_Name = variable value Example: Stdnmbr = 1 Variable_Name = variable value; Example: Stdnmbr = 1; Variable1, Variable2 = value1, value2 Example: Std1, std2 = 1, 2 Variable1, Variable2 = value1, value2; Example: Std1, std2 = 1, 2;
The global variable is declaring variable name which is using entire coding.
The global variable does not need any keyword to declare the name.
The global variable identifies using only variable names and their values.
2. The local variable:
The local variable syntax is below.
local Variable_Name = variable value Example: local Stdnmbr = 1 local Variable_Name = variable value; Example: local Stdnmbr = 1; local Variable1, Variable2 = value1, value2 Example: local Std1, std2 = 1, 2 local Variable1, Variable2 = value1, value2; Example: local Std1, std2 = 1, 2;
The local variable is declaring variable name inside of the method, chunk, and function.
The variable is used the “local” keyword to declare the local variable name.
3. The table variable:
The table variable syntax is below.
Variable_name = {}
The table variable initializes the Lua table.
Variable_name[ index ] = “information”
The table variable assigns the value to the index.
Variable_name = nil
The table variable removes the reference of the table.
The table variable is using to create a Lua table in the code.
The variable and Lua table do not have any fixed relation for data storage.
The variable used to create a table, assign value and remove the reference table.
The variable contains every value but not the nil value of the table. The nil value is used to remove the table reference.
How to work variables in Lua?Step 1:
The Lua text editor, Lua compiler, and Lua interpreter install in your computer as per the operating system and software version.
Or
If you do not have the software, then you can use Lua Online IDEs for coding and start Lua programming.
Step 2:
The Lua file creates with the .lua extension and writes a source code.
Step 3:
If the user required a global variable, then write Lua global variable syntax.
Stdnmbr = 1
If the user required a local variable, then write Lua local variable syntax.
local Stdnmbr = 1
If the user required a table variable, then write Lua table variable syntax.
Stdnmbr = {} Stdnmbr[1] = “Lua”a = 11; print(“global variable: “, a) local x = 10 print(“local variable: “, x)
ExamplesLet us discuss examples of Lua Variables.
Example #1The Lua global variable with value example and output.
Code:
a1 = 11; print("global variable: ", a1) x1 = 12; print("global variable: ", x1) y1 , z1 = 13, 14 print("global variable: ", y1, z1) b1 , c1 = 16, 11; print("global variable: ", b1, c1) d1, e1 = print("global variable: ", d1, e1) f1, g1 = 21 print("global variable: ", f1, g1)The multiple variable name and value can use a single time to declare variables. If the value is not assigned but the equal sign is assigned to the variable name then the variable value becomes nil.
Output:
Example #2the Lua local variable with value example and output.
Code:
local a1 = 11; print("local variable: ", a1) local x1 = 12; print("local variable:: ", x1) local y1 , z1 = 13, 14 print("local variable:: ", y1, z1) local b1 , c1 = 16, 11; print("local variable:: ", b1, c1) local d1, e1 = print("local variable:: ", d1, e1) local f1, g1 = 21 print("local variable:: ", f1, g1)Output:
Example #3the Lua table variable with value example and output.
Code:
luaVariable = {} print(" initialize table using variable", luaVariable) luaVariable[2] = "lua" print(" Assign value 1", luaVariable[2]) luaVariable["tut"] = "tutorial" print(" Assign value 2", luaVariable["tut"]) luaVariable = nil print(" remove the reference", luaVariable)Description:
If we initialize the table using a variable then we get the memory location of the table. If we assign nil value to the variable then the reference is removed and the variable becomes nil.
Output:
Example #4the Lua variable name with case sensitive example and output.
Code:
local _a1 = 11; print("Lua case sensitive variable: ", a1) print("Lua case sensitive variable: ", _a1) print("Lua case sensitive variable: ", _A1) local A1 = 12; print("Lua case sensitive variable:: ", a1) print("Lua case sensitive variable:: ", A1) local y , z_1 = 13, 14 print("Lua case sensitive variable:: ", y, Z_1) print("Lua case sensitive variable:: ", y, z_1) m , s = 43, 44 print("Lua case sensitive variable:: ", S, M) print("Lua case sensitive variable:: ", s, m)Description:
You can see the above example with variable names. The s and S letter is different for language due to Lua is case sensitive language. The underscore symbol and uppercase and lowercase letter can use to start the variable name. The number is not allowed to start variable name but after the first letter allowed to use in the variable name.
Output:
Example #5the Lua variable example and output.
Code:
luaVariable = {"online", "habit", "to", "learn"} print("write table variable value using global variable") for globlev = 1, 4 do print(luaVariable[globlev]) end print("write the relation between Lua local variable and Lua global variable") glv = 12 local lv = 15 if lv < 16 then local glv = 12 print(glv + 5) else print(glv); end print(glv);Output:
ConclusionThe Lua variable is the key factor of the memory location and data storage in the Lua application. The Lua variable helps to initialize the data, assign, modify, and return the data or information. The Lua variable avoids the complication of the memory location and data storage.
Recommended ArticlesWe hope that this EDUCBA information on “Lua Variables” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading How Variables Work In Lua With Examples?
How Logging Work In Scala With Examples
Introduction to Scala Logging
Logging is used to maintain the logs of an application. It is very much required to monitor our application. Logging helps us to monitor the activity of our application in case if any error occurs we can check it from the logs and fix it. We can also get the information about what activity is going on into out application. we can have day to day task and full monitoring of applications. It also keeps track of the unusual errors or circumstances which can lead down fall of our application. Majorly it is very helpful for the developers to keep track of all the actions performed and the error occurs if any.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
In scala also we have three levels of logging which are debug, info and error. But we need to set this in our application configuration which level we want to use. This levels will be different according to different environment lets discuss them with syntax see below;
Debug level syntax; debug(our message) Info level syntax; info(our message) Error level syntax; error(our message)In this way we can define them our application and we have to enable the log level accordingly and also make entries into configuration to make them work.
How Logging Work in Scala?Scala logging is important and works like any other programming language. To keep track of our application we can use logging it can be used with different levels. To apply logging we can simply use scala logging for this. Scala provides us one logger class which is present inside this com.typesafe.scalalogging package also this class internally wraps the SLF4J logger. To use scala logging we have to pass or give a name to one of the method available in Logger object. We will see this by syntax see below;
We can pass the name in many different ways we can discuss them in details with one practice example for beginners for better understanding of logging concept;
1. In this we can pass the name directly to the Logger class.
vallogger_name = Logger("any_name")In this syntax, we just have to give the name for the logger and one logging name pass as parameter inside the Logger class.
2. In this case, we can wrap our class by the implicit tag parameter.
vallogger_name = Logger[Your_Class_Name]In this syntax, we are passing our class to the implicit tag parameter.
3. In this case, as we know this scala logging internally use SLF4J, so we can pass the name to the SLF4J logger instance also.
vallogger_name = Logger(LoggerFactory.getLogger("any_name"))4. In this, we pass inside the class.
vallogger_name = Logger(classOf[Your_Class_Name])Inside this package com.typesafe.scalalogging it provides us two traits which are Strict Logging and Lazy Logging and they are responsible to define the logger as Strict or Lazy.
Now we have one more this which is called Application logging: Application logging keeps track of our application at runtime and maintains all the logs. But sometime it may happen that we want all the logs of our application so we have to maintain the audit of logging and this can be achieved by storing our runtime application logs somewhere like database, into a disk, or search engine etc.
There are some things which all application wat to capture as a log;
As we talked about the log levels i.e. information, error, and warning.
The most important thing is the timestamp.
Some relevant messages make any sense after some time also.
The log levels define various things see below;
Error: Error is something which is serious and shows something wring with our application it is not behaving normal as expected. This can be anything like related to database connection; some services are not available or stopped due to some failure etc. So this is very important to fix and make our application again up and running.
Debug: Debug level is something like when we perform our diagnosis regarding the application. Like if we are making any request for data to the database so is it working properly and fetching all the data that is applicable regarding the request we have made.
Trace: This is a more detailed version of the debug level. When we want to know the very precious value than we go for Trace in scala logging.
Examples of Scala LoggingIn this example, we are using Print Writer and File to maintain our logs in scala. We will create a file into our system and going to maintain the logs there.
Example #1Code:
import java.io.{File, PrintWriter} object LoggingDemo extends App { val pw = new PrintWriter(new File("logging_demo.log")) pw.write("logging file has been created") pw.write("loggers working fine") pw.close() } Example #2In this example, we are using slf4j to log the activity of our program. We have using different methods available for logging like debug, error, and info.
Code:
import org.slf4j.LoggerFactory object Main extends App { valmy_logger = LoggerFactory.getLogger(getClass.getSimpleName) my_logger.info("Here we are using info method !!!! ") my_logger.debug("Here we are using debug method !!!! ") my_logger.error("Here we are using error method !!!! ") println("logges been created. !!!") }Output:
ConclusionWe use logging for monitoring purposes. Which helps us to behave our application as expected. We can also provide different logging levels as well. We can maintain any number of lines to log out application activity we can also store them somewhere into the file for the future purpose also these file representation makes it easier to understand.
Recommended ArticlesWe hope that this EDUCBA information on “Scala Logging” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Sizeof() Operator Work In C++ With Examples
Introduction to C++ sizeof()
The sizeof() is an operator in C and C++. It is an unary operator which assists a programmer in finding the size of the operand which is being used. The result of this operator is an integral type which is usually signified by size_t. This operator is usually used with data types which can be primitive data types like integer, float, pointer, etc. It can also give size of complex datatypes like structure, union, etc. It is a compile time operator which will tell the size of any data type and compute the size of operand.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Below is the syntax of using sizeof():
sizeof(type) sizeof expressionThe sizeof function in the first type, will give the output as an size in bytes of the object of the type which is sent. The second type is the size in bytes of the object which is in the type of expression. The size will be the size once the expression is evaluated. In both these versions the constant expression of the standard type that is size_t.
How sizeof() Operator work in C++?The sizeof() operator can be used to find the size of datatype or expressions. They work in a very easy manner of taking these as arguments and work on them by returning the size in bytes.
Code:
using namespace std; int main() { cout << “Size of char : ” << sizeof(char) << endl; cout << “Size of int : ” << sizeof(int) << endl; cout << “Size of expression 5 + 8 is : ” << sizeof(5 + 8) << endl; return 0; }
As stated earlier the sizeof function will help us in getting the size of every datatype. Hence it uses these data types as an argument and return the data size of each data type. We have also taken size of expression where we are adding 2 integers. It will calculate these and the result will also be an integer. Hence the output for this will be also 4. The output of above function and code will be the number of bytes each variable uses. To check a few the output for char will be as below.
Output:
Examples of C++ sizeof()Given below are the examples mentioned:
Example #1Operand as a data type.
Code:
using namespace std; int main() { cout << “The size of char data type is ” << sizeof(char)<<“n”; cout << “The size of int data type is ” << sizeof(int)<<“n”; cout << “The size of float data type is “<< sizeof(float)<<“n”; cout << “The size of double data type is ” << sizeof(double)<<“n”; return 0; }
Output:
Example #2Operand as an expression.
Code:
using namespace std; int main() { int a = 7; float d = 15.21; cout << “The addition of int and float is a float as follows: ” << a + d; cout << “nThe size of the expression is ” << sizeof(a + d); return 0; }
The above code with return the size of the data type of the resulting expression. Here we have declared two variables. One variable is an integer and the second variable is a float. We are now adding these two variables in the expression of which we will be finding the size of. The result of this expression will be a float. Hence the sizeof will be the size of float data type.
Output:
Example #3Finding number of elements in the array.
Code:
using namespace std; int main() { int array1[] = { 1,5,76,89,23,06 }; cout << “The number of elements which are present in the array are : “ <<(sizeof(array1) / sizeof(array1[0])); return 0; }
In addition to giving the size of expressions and data types, the sizeof operator can also be used to find the number of elements in an array. Here we have defined an array ‘array1’. We have a few elements added to it. In order to get the count of these elements and get exactly how many elements are present in it we can simply make use of the sizeof operator.
We specify the array name and the first index that is array1[0] which helps us in starting he count from beginning. It will start from index 0 and count till the end. Once it reached the end it will display the number of elements. It will be returned by this sizeof() function that we have.
Output:
ConclusionThe sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result which is size of that data type in bytes. If it is an array it will return the number of elements present in it. It is a very useful function when we have to allocate memory. We can calculate the size and allocate memory as per requirement and as a result save a lot of space which otherwise will be occupied.
Recommended ArticlesThis is a guide to C++ sizeof(). Here we discuss how sizeof() operator work in C++ along with examples respectively. You may also have a look at the following articles to learn more –
How Does Substring Work In Scala With Examples?
Introduction to Scala Substring
As the name suggests, a scala substring is used to get the substring from the given input. We can find out the substring by specifying any index. Substring function can be call on any string. But have to pass the index in order to use the substring method in Scala. There may be some requirement where we need to find the substring present inside the string input itself so we can go with the substring method in scala. We have two types of methods available in scala to get the substring from the given string. In the coming section, we will discuss more about this method in detail.
Start Your Free Software Development Course
Syntax
As substring string is a method available in scala used to get the substring from the specified index, Let’s see its syntax for better understanding of it and how to use this method on programming see below;
substring(int index)As we can see in the above syntax, this method takes one parameter as the input type. We can call this method on any String input. Let’s see one practice syntax to understand its real usage see below;
val demostr = "some string here" demostr.substring(3) How does substring work in Scala?As of now, we know that the substring method is used to get the string from the string in scala. It is an in build method available in scala, so we can directly use this without being involved in any library in our program. But we can find out the string by mentioning the index while using this method. This method takes one parameter as the input. We have two substring method available in scala based on the input parameter we pass. Now we will see each of them in details about the method signature and its return type; for more understanding, see below;
Method signature1. String substring(int begningIndex): This is the method signature of substring function as per the scala doc. In this method, we are passing one parameter as the input here. Let’s discuss the input param in detail see below;
int begningIndex: This parameter is used to specify the index of the substring that needs to get from the string input. This is the beginning index of the substring so that it will return the string at the end of the input string from the beginning index. For instance, we can see one example to for better understanding see below;
Example:
object Main extends App{ val str = "hellotoallbye".substring(10) println(str) }In the above code lines, we create one string named ‘str’ followed by calling the substring method on it. But here, we are passing ’10’ as the starting index for the substring. So it will start from 10 and return us the result at the end of the string. Here we are not mentioning any end index.
2. String substring(int begningIndex, int endIndex): In this method, we are passing two input parameter, and this method is also used to get the substring from the given string input. Only the method signature is different; we can call it method overloading in terms of object-oriented programming language. Let’s discuss each of the parameters in details for better understanding see below;
int begningIndex: This parameter issued to assign the value which will act as the starting point of the substring method in scala. It will work in the same way as before without any difference.
int endIndex: This parameter issued to specify the end index for the substring. Which means it will return the substring at this end index only. This index will act as the ending point for the substring where our substring will end and complete. We will see one practice example of how to use this method while programming see below;
object Main extends App{ val str = "hellotoallbye".substring(8, 10) println(str) }As you can see in the above lines of code, we are creating one string here and calling the substring method, but this time it will return as the string between the specified index only. This will act as the starting and endpoint of the substring here.
3. return type: Scala’s substring method always returns a new string between the specified index of the given string.
ExamplesHere are the following examples of Scala Substring mention below:
Example #1In this example, we are calculating the string from the beginning index only using substring in scala.
Code:
object Main extends App{ val str1 = "i am string one as input" val str2 = "i am string two as input" val str3 = "i am string three as input" val str4 = "i am string four as input" val str5 = "i am string five as input" val result1 = str1.substring(13) val result2 = str2.substring(11) val result3 = str3.substring(2) val result4 = str4.substring(5) val result5 = str5.substring(15) println("Result one is :: " ) println(result1) println("Result two is :: " ) println(result2) println("Result three is :: " ) println(result3) println("Result four is :: " ) println(result4) println("Result five is :: " ) println(result5) }Output:
Example #2In this example, we are using the start and end index to get the substring using the substring in scala.
Code:
object Main extends App{ val str1 = "i am string one as input" val str2 = "i am string two as input" val str3 = "i am string three as input" val str4 = "i am string four as input" val str5 = "i am string five as input" val result1 = str1.substring(12, 16) val result2 = str2.substring(12, 16) val result3 = str3.substring(12, 16) val result4 = str4.substring(12, 16) val result5 = str5.substring(12, 16) println("Result one is :: " ) println(result1) println("Result two is :: " ) println(result2) println("Result three is :: " ) println(result3) println("Result four is :: " ) println(result4) println("Result five is :: " ) println(result5) }Output:
ConclusionBy the use of it, we can get the substring from the given string. It will always return us a new string. Also, it is the build method available in scala, so it is easy to use and readable like any other programming language like java.
Recommended ArticlesWe hope that this EDUCBA information on “Scala Substring” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Does Pop Function Work In Perl With Examples
Introduction to Perl pop
Web development, programming languages, Software testing & others
Syntax:
The Perl script uses some data structure concepts like push and pop. It is mainly used for manipulates the data, and it reduces the memory to perform the operations quickly. The pop() functionality have to remove the last element from the array or any other data structures in the memory.
@var =(' '); print pop(@var); ----some perl script codes depends upon the user requirement the perl functions will be called and used in the file---The above codes are the basic syntax for the pop() function used in the Perl script; the user input values are popped out on the data structures.
How does the pop Function work in Perl?
The Perl script uses some default functions, keywords, variables for creating the sophisticated applications. Likewise, we use some data structures concepts like an array, stack, queue, push, pop, shift etc., for securing the datas as well as reduce the data usages in the memory location. Perl array uses a pop() function for removing the last element of the array; it also pointed out the stack in data collections and structure concepts. It also used for to remove as well as return or pop the last element from the array.
This is meant by to reduce the number of elements in the array. Generally, the last stage or position of the element is the highest level of the index is generated automatically in the stack memory. Also, the pop() function of the elements are chopped off the elements from the right side positions of the array list, and it will return the element as soon as to reduce the element size automatically with one by one in the memory. The array elements are also thought of as the stack for the numbered boxes that are top to bottom, and increasing the element size goes down so that the bottom of the stack memory is popped out in the memory.
Examples of Perl popGiven below are the examples of Perl pop:
Example #1Code:
#!/usr/bin/perl -w @var = (7654,3876,2736,91237,237,9273,36483,12973,2739,918723,9273,8263,912873,9812732,973924,192873184,9210838,91723,90238,921838); print("Welcome To My Domain", pop(@var), "After using the pop() function in the script it return the value as recently removed in the list",@var, "n")Output:
In the above example, we used a basic variable like @var to initialise the values; it will be lengthy to store them in the array. So each value has a separate reference, and it holds the reference to the stack memory location because when we removed the particular element in the stack, it also holds the reference keep on the memory so the memory loss will be occurred due to avoid the memory leaks and consumption it removes in the memory. If we use the pop() function, it removes the last element in the array that is left to right position; the last position of the element is 921838 it will be removed in the stack memory.
Example #2Code:
use strict; use warnings; my @var = qw(+ - * / %); pop @var; print "Welcome To My Domain its the first pop() function used in the stack memory n n @varn"; print "After Inserting the aboev two operators in the stack memory the variable and the array size is shown n n @var n"; my @var1 = qw(74 dg dgh wehf whewf jh e wiejh eih eihrf 3748 jh48 hef 4897y jhef 4 9y8 hr 9 4 herfu9 jkd jdeij iejhfb wefih); pop (@var1); unshift @var1, 'Have a Nice Day User'; print "After using the unshift() function in the pop() functionality the stack memory of the varaible is shown n [email protected]n"; my @demo = ('1'..'100'); unshift(@demo, pop(@demo)); print "We compared the unshift() functionality in the pop() function the result is: n n@@demo = @@demon";Output:
In the second example, we used some different functions like unshift and push() in pop() functionality. After removing the last element in the stack, the memory reference of the particular value has also been empty. It is in null space, so it will be occupied with the other elements by using the push() operation; it will be inserted in the array list. When we use unshift() function, we can call the pop() function and the user input variable to compare the two functionality in the script. Here we used 1..100 in the variable @demo; it will be called in the unshift(@demo, pop(@demo)) method for comparing the same variable values for the different purposes.
Example #3 use strict; use warnings; print "Welcome User after using the split() function in pop() out the result is: n $varn"; my $var1 = ['55gtg', 'fu', 'erhgfb', 'jwehg', 'jehwgfvj']; pop @$var1; print "Have a Nice day user after popped out the elements from the array list is: @{$var1}n"Output:
ConclusionIn concluded part, the Perl script used a lot of default methods with their properties in the application. Likewise, pop() is one of the pretty functionality for the data structure using the Perl script. Using these functions, we will remove the last element from the data structure and reduce the memory.
Recommended ArticlesThis is a guide to Perl pop. Here we discuss the introduction; how does pop function work in Perl? and examples, respectively. You may also have a look at the following articles to learn more –
How Does React Fragment Work With Examples
Introduction to React Fragment
React Fragments were first launched in the version React 16.2.0. These are used where, earlier, the developers used wrapper div as React Fragments help us group a set of children without adding additional nodes to the DOM. Earlier, the elements were wrapped in a div for returning multiple aspects. This led to some irrelevant markup or rendering of irrelevant HTML, which could have been better for the website. React Fragments solved this problem. This easily returns multiple elements without the need for a wrapper div. This article will explain how to use this with some examples.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax:
render() { return ( ); } How does React Fragment work with Examples? 1. Short ExampleComponents inside src folder:
index.js
style.css
chúng tôi
import React from 'react' import ReactDOM from 'react-dom' function App() { return ( ) }chúng tôi
.App { font-family: 'Times New Roman', Times, serif, sans-serif; text-align: center; }Output:
2. BasicComponents inside src folder:
chúng tôi
import React , { Component , Fragment } from "react"; import { render } from "react-dom"; class Columns extends Component { render() { const heros = [ { name: 'Dr. Strange', id: 1 }, { name: 'Ironman', id: 2 }, { name: 'Rocket', id: 3 } ]; return ( <Fragment key={hero.id {hero.name } is SUPER AMAZING!!.... ))} ); } } class Table extends Component { render() { return ( ); } }Output:
3. With SignIn and SignOut buttonsComponents inside src folder:
config folder
admin.js
home.js
login.js
index.js
Components inside config folder:
switch.js
routes.js
chúng tôi
import { Switch } from "react-router-dom"; import React , { Fragment } from "react"; export default function FragmentSupportingSwitch({ children }) { const flattenedChildren = []; flatten(flattenedChildren, children); return React.createElement.apply( React, [Switch, null].concat(flattenedChildren) ); } function flatten(target, children) { if (React.isValidElement(child)) { if (child.type === Fragment) { flatten(target, child.props.children); } else { target.push(child); } } }); }chúng tôi
import React , { Fragment } from "react"; import { Router , Route } from "react-router-dom"; import Switch from "./Switch"; import createBrowserHistory from "history/createBrowserHistory"; import Login from "../Login"; import Home from "../Home"; import Admin from "../Admin"; export const history = createBrowserHistory(); return ( {!isLoggedIn && ( )} ) : ( <Route exact path="/admin" )} ); }; export default Routes;chúng tôi
import React from "react"; ); import React from "react"; import { Link } from "react-router-dom"; );chúng tôi
import React from "react"; );chúng tôi
import React from "react"; import { render } from "react-dom"; import Routes from "./config/routes"; class App extends React.Component { state = { isLoggedIn: false }; this.setState({ isLoggedIn: true }); }; this.setState({ isLoggedIn: false }); }; render() { return ( <Routes login={this.login} logout={this.logout} isLoggedIn={this.state.isLoggedIn} ); } }Output:
4. With SwitchComponents inside src folder:
chúng tôi
import React from "react"; import ReactDOM from "react-dom"; import { Switch as BaseSwitch , Route , BrowserRouter , Link } from "react-router-dom"; import flattenChildren from "react-flatten-children"; ); class App extends React.Component { state = { private: false }; render() { return ( <button type="button" > {this.state.private ? "Sign Out" : "Sign In"} {this.state.private && ( )} {this.state.private && ( )} ); } } const rootElement = document.getElementById("root");Output:
5. With Render FragmentFiles to develop this:
fragment.js
Hello.js
index.html
index.js
chúng tôi
import React from 'react'; import PropTypes from 'prop-types'; const [reactMajorVersion] = React.version.split('.'); Wrapper : React.Children.toArray(children) ); if (process.env.NODE_ENV !== 'production') { RenderArrayOrDiv.propTypes = { as: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), children: PropTypes.node.isRequired, }; } RenderArrayOrDiv.defaultProps = { as: canReturnArray ? undefined : 'div', }; console.log(React.Fragment); const Fragment = React.Fragment ? React.Fragment : RenderArrayOrDiv; console.log(Fragment); export default Fragment;chúng tôi
import React from 'react';index.html
chúng tôi
import React from 'react'; import { render } from 'react-dom'; import Fragment from 'render-fragment'; import Hello from './Hello'; );Output:
ConclusionIn this article, we understood This and why it is so helpful to the developers. We went through five different examples to understand the different ways to use this same. This is easy to use, and I hope this article would have explained the ways to use it in a simple and meaningful way.
Recommended ArticlesWe hope that this EDUCBA information on “React Fragment” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Update the detailed information about How Variables Work In Lua With Examples? on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!