What we’ll learn in this part:
- More on JSX
- What is arrow function in JavaScript
- What is map function
- Using map function to iterate data in JSX
- Part One
- Part Two
More on JSX
Let’s learn more about JSX as this will help us in fixing most common issues while working with React/JSX.
JSX is:
- HTML like syntax in which you can write JavaScript expressions in curly braces.
- OR JavaScript code in which you can use HTML like tags.
With JSX, when we are writing HTML & want to write some JavaScript within it, we need to use curly braces {}. We can’t have multiple statements in this. So can we use a “for” loop or if statement in these curly braces? The answer is "No". If we need to have complex logic which requires multiple statements (or curly braces), we should create a separate function and then call that function in JSX curly braces or prepare final result separately and place that in curly braces.
User defined components must be capitalized.
When we start element with lower case, React refers to built-in tags (e.g. div, h1).
For example, in following code “MyName” is started with lowercase (“myName”) so React will think that it is HTML tag.
- <script type='text/babel'>
- function MyName(props){
- return <h3>{props.name}</h3>
- }
-
-
- function MyApp(){
- return (
- <div class="maincontainer">
- { }
- <MyName name="Bilal Shahzad 1" />
-
- { }
- <myName name="Bilal Shahzad 2" />
- </div>
- );
- }
-
- ReactDOM.render(<MyApp />,document.getElementById('app'));
- </script>
If we check on the console, we’ll see the following error:
Assume these tags are objects and yes they are, i.e., React Elements.
If these tags are objects, can we store them in some variable? Can we add them in an array? Can we pass them to a function? Can we return them from a function? Yes, we can.
- function MyApp(){
-
- var o = <Profile name="Bilal Shahzad" url="https://www.youtube.com/c/LearnInUrdu139" urlText="Learn in Urdu Tutorials" />
- console.log(o);
-
- return o;
- }
If we check output on console, we can see that it is a React element which contains ‘props’ property in it.
Here is another example
- function MyApp(){
- var h = <h3>Profiles</h3>
- console.log(h);
- var o = <Profile name="Bilal Shahzad" url="https://www.youtube.com/c/LearnInUrdu139" urlText="Learn in Urdu Tutorials" />
- var o1 = <Profile name="Faisal Shahzad" url="https://www.youtube.com/c/LearnInUrdu139" urlText="Learn in Urdu Tutorials 2" />
-
- return [h,o,o1];
- }
And here is output on console, Note: we’ve used HTML tag (h3) and we can see it is also a React element which will produce h3 tag in browser.
Note
When we want to return multiple elements from our component without a parent, we can return array element as used above. Here is another example.
- function MyApp(){
- var h = <h3>Profiles</h3>
-
-
- return (
- [
- h,
- <Profile name="Bilal Shahzad" url="https://www.youtube.com/c/LearnInUrdu139" urlText="Learn in Urdu Tutorials" />,
- <Profile name="Faisal Shahzad" url="https://www.youtube.com/c/LearnInUrdu139" urlText="Learn in Urdu Tutorials 2" />
- ]);
- }
Let’s update our MyApp component and render different profiles programmatically.
Let’s assume we have data as an array of objects. We want to generate Profiles based on this data. We need to iterate this array and generate Profile components. But we can’t use for loop in JSX curly braces so we’ve prepared our result separately and then just placed that in curly braces to render it.
- <script type='text/babel'>
- function MyName(props){
- return <h3>{props.name}</h3>
- }
- function ProfileLink(props){
- return <a href={props.url}>{props.urlText}</a>;
- }
-
- function Profile(props){
- return (
- <div class="mycontainer">
- <MyName name={props.name} />
- <ProfileLink url={props.url} urlText={props.urlText} />
- </div>
- );
- }
-
-
- function MyApp(){
-
-
- var data = [
- {name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},
- {name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"}
- ];
-
-
- var result = [];
- for(var i=0;i<data.length;i++){
- var obj = data[i];
- result.push(<Profile name={obj.name} url={obj.url} urlText={obj.urlText} />)
- }
-
- return (
- <div class="maincontainer">
- {result}
- </div>
- );
- }
-
- ReactDOM.render(<MyApp />,document.getElementById('app'));
- </script>
Let’s update the above code & create another component, Profiles, to hold this logic. We are passing ‘data’ object in props.
- <script type='text/babel'>
- function MyName(props){
- return <h3>{props.name}</h3>
- }
- function ProfileLink(props){
- return <a href={props.url}>{props.urlText}</a>;
- }
-
- function Profile(props){
- return (
- <div class="mycontainer">
- <MyName name={props.name} />
- <ProfileLink url={props.url} urlText={props.urlText} />
- </div>
- );
- }
-
- function Profiles(props){
- var data = props.data;
-
- var result = [];
- for(var i=0;i<data.length;i++){
- var obj = data[i];
- result.push(<Profile name={obj.name} url={obj.url} urlText={obj.urlText} />)
- }
- return result;
- }
-
-
- function MyApp(){
-
-
- var data = [
- {name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},
- {name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"}
- ];
-
- return (
- <div class="maincontainer">
- <Profiles data={data} />
- </div>
- );
- }
-
- ReactDOM.render(<MyApp />,document.getElementById('app'));
- </script>
Can we achieve above funtionality with less code? Let's learn a couple of concepts before that.
Arrow functions in JavaScript
Arrow function is a new style to write anonymous function in JavaScript. This syntax was introduced in ES6 (ECMAScript 2015). Some important points regarding arrow functions are,
- No ‘function’ keyword is used.
- Parentheses are used to declare parameters.
- Arrow operator (=>) is used to indicate function body.
- Curly braces of body can be skipped if function has only one statement. If function has only one statement, no need to use ‘return’ statement.
- Curly braces can be used if there are multiple statements and ‘return’ will have to be used explicitly if function is going to return something.
Here are some examples of how we can create arrow functions.
- <script>
-
- var f1 = () => console.log('Arrow function without body');
-
- var f2 = () => {
- console.log('Arrow function with body');
- }
-
-
- var f3 = (a,b) => a+b;
-
- f3(5,10);
-
-
- var f4 = (a,b) => {
- return a+ b;
- }
-
- f4(15,20);
-
-
-
-
- var f5 = a => a*5;
-
-
-
-
-
-
-
- </script>
Array map() function
Map function takes a (callback) function as input parameter and executes that function for every element of the array. It prepares a new array based on the returned values.
- <script>
- function Test(value,index,Arr){
- return 'v is ' + value;
- }
- var arr = [1,2,3,4];
- var res = arr.map(Test)
- console.log(res);
-
- <script>
Here is another example using Anonymous function:
- <script>
-
- var arr = [1,2,3,4];
- var res = arr.map(function(value,index,Arr){
- return 'v is ' + value;
- });
- console.log(res);
-
- </script>
Another example
- <script>
- var arr = [1,2,3,4];
- var res = arr.map(function(value,index,Arr){
- if(value%2 == 0)
- return 'even';
- else
- return 'odd';
- });
- console.log(res);
-
- </script>
Note
map function should not be used if
- We are not using the array it returns
- OR We are not returning anything from callback function
Instead we should use forEach.
Now let’s update our React example but using arrow function syntax and JavaScript map function to clean our code (and yes, it becomes less readable if we don't have a good understanding of these concepts).
- <script type='text/babel'>
- function MyName(props){
- return <h3>{props.name}</h3>
- }
- function ProfileLink(props){
- return <a href={props.url}>{props.urlText}</a>;
- }
-
- function Profile(props){
- return (
- <div class="mycontainer">
- <MyName name={props.name} />
- <ProfileLink url={props.url} urlText={props.urlText} />
- </div>
- );
- }
-
- function Profiles(props){
-
- return props.data.map((obj)=>(<Profile name={obj.name} url={obj.url} urlText={obj.urlText} />));
- }
-
-
- function MyApp(){
-
-
- var data = [
- {name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},
- {name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"},
- {name:"Waqas Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 3"},
- {name:"Khurram Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 4"}
- ];
-
- return (
- <div class="maincontainer">
- <Profiles data={data} />
- </div>
- );
- }
-
- ReactDOM.render(<MyApp />,document.getElementById('app'));
- </script>
In the next part, we’ll learn how we do event handling in React.
Summary
We learnt more about JSX and then we learnt map & arrow functions as those are extensively used while working with React.
For more details,
- https://reactjs.org/docs/jsx-in-depth.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions