DEV Community

Simon Lee
Simon Lee

Posted on

Comparing React and Vue - part 2

This is my 2nd post for my React & VueJS comparisons... purely for learning and understanding the basics of these 2 frameworks a little better. Here's Part 1.

Let's look at basic conditional statements in Vue

<p v-if="show">conditional example</p>
Enter fullscreen mode Exit fullscreen mode

In your Vue instance's data, if you set "show" to equal true, this paragraph will show in the DOM. If "show" is set to false, it hides this paragraph.

var myapp = new Vue({
  el: '#my-app',
  data: {
    show: true
  }
})
Enter fullscreen mode Exit fullscreen mode

There's also a v-else directive that you can use after a v-if.

<div v-if="show">First Div</div>
<div v-else>Second Div</div>
Enter fullscreen mode Exit fullscreen mode

Now, if you set show to false, the DOM will display the text "Second Div".

Conditional Rendering in React

In React, to do if-else conditional rendering, it will involve writing a little more javascript compared to Vue.

Inside your render() function, and before you return your JSX template, you'll need to assign this.state to your condition variable. You also need to create a function that includes your condition logic.

render() {
  let {isLoggedIn} = this.state;
  const showOneButton = () => {
    if (isLoggedIn){
      return <button>Logout</button>
    } else {
      return <button>Login</button>
    }
}
Enter fullscreen mode Exit fullscreen mode

Inside your JSX return () statement, you call that function:

return (
      <div>
        { showOneButton() }
      </div>
    );
Enter fullscreen mode Exit fullscreen mode

You could refactor this using Ternary Operators, or a switch statement. There's also the Logical && Operator. So plenty of options, and some are more elegant than others. Try them out and have fun!

Top comments (0)