5. React JSX and Expressions inDepth

We will learn deep into JSX and JSX expressions with multiple elements, nested elements and dynamic data.


 

We will make it dynamic instead of putting static data. 

We will create complex expression. The JSX code to be wrapped.

To Prevent JSX syntax error add all JSX elements into <div></div>

All JSX elements to be placed into single root <div>. This will wrap everything.

Var template = (<div>

<h1>Welcome to Sleepy coder Blog | React JSX expressions</h1>

<p>React JSX and Expressions inDepth</p>

</div>);

JSX Expressions:

Lets fetch values dynamically in jsx. Display the variables using { }  curly braces.

var name = 'Prabakaran Palanichamy';

const template = (<div>

<h1>My Name is : {name} </h2>

<h2>My Name is uppercase: {name.touppercase()} </h2>

</div>);

let userObj = {

name: 'praba',

age: 30,

location: 'Bangalore'

};

var template = (<div>

<p>Name: {userObj .name}</p>

<p>Age: {userObj .age}</p> 

<p>Location: {userObj .location}</p> 

</div>);

ReactDOM.render(template, document.getElementById('app')); 


If we print this object directly it will throw an error in the browser.

Conditional Rendering JSX:

It is nothing but conditional logic

for example If the user is loggedin show logout button. If the user not logged in show login button.

  1. JavaScript expressions can be used inside of JSX. We just need to wrap it with curly brackets {}.
  2. You can use if-else statements inside JSX, instead, you can also use conditional (ternary) expressions.

 We will use functions and will put conditions. and we will put arrow functions.

funtion getName() {

     return 'unknown';

}

var template = (<div>

<h1>Name: {getName} </h1>

</div>);

 Pass argument in getName()

funtion getName(name) {

if(name){

     return name;

}else{

    return 'unknown';

}

let userObj = {

name: 'praba',

age: 30,

location: 'Bangalore'

};

 

var template = (<div>

<h1>Name: {getName(userObj .name)} </h1>

</div>);

If we want to have any conditional logic we should define in function like mentioned above.

We have used function call with if statements.

Lets see how to use ternary operator .

We will have conditional logic.


 
Ternary operator is an expression. it is not a statement.
we no need to have this in separate function.
we can have it on same line
<h1>{userObj .name ? userObj .name : 'unknown' } </h1>
 
Logical Operator:

{true} {false} {null}

undefined, null, booleans are ignored in jsx.

 
The logical && operator helps you to make conditions that would return null more concise. How does it work? In JavaScript a true && 'Praba' always evaluates to Praba and a false && 'praba' always evaluates to false. In React you can make use of that behaviour.
 

We will learn more about const and let in the next tutorial.





 


Comments