How to write if statement in React.js?

duomly

Duomly

Posted on July 29, 2020

How to write if statement in React.js?

This article was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-2/#how-to-write-if-statement-in-react-js


Of course, if we think about if statement in Javascript or Typescript logic, it’s the same as in every Javascript or Typescript place.

It’s just if/else like pure javascript, but in this case, we won’t talk about the normal if/else.

In react, we’ll need if statements for the one more thing, it’s the rendering.

It’s named “Conditional rendering”, but to make it simple, let’s stay with “if statement in react”.

There are the two most popular ways to use conditional rendering that we’ll see in the React.js code, and depends on a case, both of them are correct.

The first way that we can use is to define the conditional rendering directly in the components layout.

It’s quick and easy that we’ll use the most, and in some cases, it is the best for performance.

We’ll be using this way in the cases when we have only one condition, more just as “if”, when we would like to render some element when a specified condition is passed.

The second way is the function created to handle specified parts of the layout, and render it conditionally, to do that we can use not only if/else but the switch case as well.

This one way is right to use in cases where we have more conditions, especially the version with switch one.

But it fires the function anyway, so it is no sense to use it when we have one condition.

Let’s take a look at the code examples where I added both ways of doing that:

// The first example with the code inside functional component
function Parent(props) {
  return(
    <>
      {name === "Duomly" && (
        <DuomlyComponent/> 
      )}
    </>
  )
}

// The second example with the additional function
function renderComponent() {
  const name = 'Duomly';
  if (name === 'Duomly') {
    return 'Duomly';
  } else {
    return null;
  }
}

function Parent(props) {
  return renderComponent();
}
Enter fullscreen mode Exit fullscreen mode

Duomly - Programming Online Courses

Thank you for reading,
Radek from Duomly

💖 💪 🙅 🚩
duomly
Duomly

Posted on July 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related