loading...

Comparing React and Vue - part 2

simonhlee97 profile image Simon H Lee ・1 min read

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>

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
  }
})

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>

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>
    }
}

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

return (
      <div>
        { showOneButton() }
      </div>
    );

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!

Posted on by:

simonhlee97 profile

Simon H Lee

@simonhlee97

I enjoy building apps with Vue, Vuex, MongoDB, Node, Express (MEVN stack) as well as React (MERN stack). I also build custom WordPress themes.

Discussion

markdown guide