Conditional rendering in React

Conditional rendering in React

In this post we will give you information about Conditional rendering in React. Hear we will give you detail about Conditional rendering in ReactAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to render the elements conditionally in react.

What is conditional rendering?

Conditional rendering means only display the elements in the UI, if a particular condition is true otherwise hide the elements.

IF/ELSE conditionals

Let’s look into JavaScript if-else conditionals.

let num = 2if(num === 2){    console.log('the given number is 2')}else{    console.log('the give number is not 2')}

In the above code, we have initialized a variable with 2 then we used if else conditional to log the message based on the provided number.

Let’s implement the if/else conditional in react.js.

function App(props){   if(props.num === 2){       return <p>The given number is 2</p>   }else{       return <p>The given number is not  2</p>   }}<App  num = {2} />

In the App component we passed num prop to 2 so that we can only render the p element present inside the if condition.

Ternary operator

We can make our App component code shorter by using the ternary operator.

function App(props){    {props.num === 2 ?  <p>The given number is 2</p> :     <p>The given number is not 2</p> }}<App  num = {2} />

Here we wrapped our code with curly braces because in react jsx we need to use curly braces for the JavaScript expressions.

Logical &&(and) operator

In JavaScript, the Logical && operator is used to evaluates the expression if the given condition is true.

true && expression // expressionfalse && expression // false

Using logical and (&&) operator in react.

function Search(props){   return (       <div>          <h1>Search</h1>         <button>Search</button>         {props.searchResults > 0 &&  <ul>search results</ul>}       </div>   )}

In the Search component we used Logical &&(and) operator to render the ul element only if props.results is greater than 0.

Hope this code and post will helped you for implement Conditional rendering in React. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US