skip to Main Content

how to check the condition in render function to print friendly names
example if (value =101) then "some text ", else if (value = 102) then "Another text" etc
Please check the code below what I am trying.

public render(): React.ReactElement<IGetSpListsProps> {
return (
<div>
<ol>
{
this.state.sitecontents.map(function(mylists,mylistitemkey){
return(
<li>
  <span>{mylists.Title}</span> //here it will display list titles
  
  if({mylists.BaseTemplate} = {'101'} // basetemplate will return int number like 100, 101, 103 etc so checking the condition with 101
  {
    <p>{"Generic List template"}</p>
  }
  else if ({mylists.BaseTemplate} = {'102'}) {
    <p>{"Document List template"}</p>
  } else {
    <p>{"Custom template"}</p>
  })
  
  </li>);
  })
}</ol></div>
  );

{mylists.BaseTemplate} will return template number so i want to print friendly name to that template number, I am trying to print but its not expected. please check the output how its displaying
If we see the below screenshot the condition is considering as simple text

enter image description here

How to check condition using if else
Or is there any way to create a file/Json values and lookup from that file to get correspond friendly string?

3

Answers


  1. Instead of using comparison operator (== or ===), you are using assignment operator (=) which always causes the first block of code to be executed. Also, you can use ternary operator like the following way:

    ....
    {mylists.BaseTemplate === 101 ? (
      <p>{"Generic List template"}</p>
    ) : mylists.BaseTemplate === 102 ? (
      <p>{"Document List template"}</p>
    ) : (
      <p>{"Custom template"}</p>
    )}
    ....
    
    Login or Signup to reply.
  2. You can not use if - else keywords inside JSX. You can use if and else and return different JSX or use ?: inside JSX as follows

    Change following

    if({mylists.BaseTemplate} = {'101'} // basetemplate will return int number like 100, 101, 103 etc so checking the condition with 101
      {
        <p>{"Generic List template"}</p>
      }
      else if ({mylists.BaseTemplate} = {'102'}) {
        <p>{"Document List template"}</p>
      } else {
        <p>{"Custom template"}</p>
      })
    

    to

    <li>
      <span>{mylists.Title}</span>
      {
        mylists.BaseTemplate == '101' ? 
            <p>{"Generic List template"}</p> :
            mylists.BaseTemplate == '102' ? 
               <p>{"Document List template"}</p> :
               <p>{"Custom template"}</p>
      }
    </li>
    
    Login or Signup to reply.
  3. Have you tried the state? You can get the idea from here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search