DEV Community

Simon Lee
Simon Lee

Posted on

3

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay