Click Counter in React and Vue.js

This post is part of my React and Vue.js code by example series. My objective is to help developers with their transition in learning React to Vue.js or vice versa. This is not a comparison of which one is the best but rather to show how it is done. Let’s get started.

Knowing how to register a button click that changes a value on another component is one of the important concepts when working with these frameworks (React is a library though).

Click Counter in React

<div id="root"></div>

React uses JSX which is a bit confusing if you are coming from Vue.js because the aesthetic code (HTML) and JavaScript code comes together but stop nagging about it and keep coding. Learn more about JSX from https://reactjs.org/docs/introducing-jsx.html

class Button extends React.Component {
  constructor(props) {
    super(props);
  }
  
  render() {
    return <button onClick={this.props.clickHandler}>Click</button>        
    )
  }
}

class Counter extends React.Component {
  constructor(props) {
    super(props);    
    this.state = {clickCounter: 42};
    this.btnClickHandler = this.btnClickHandler.bind(this);
  }
  
  btnClickHandler() {
    this.setState({clickCounter: this.state.clickCounter + 1});    
  };
  
  render() {
      return (
        <>
           <h2>{this.state.clickCounter}</h2>
           <Button clickHandler={this.btnClickHandler} />
        </>
   )}
}

ReactDOM.render(<Counter />, document.getElementById('root'));

In React you don’t need to declare the component properties explicitly. For example in line 27, the clickHandler is a property and used it via this.props at line 7.

See the Pen Click Counter – React by John Pili (@johnpili) on CodePen.

Click Counter in Vue.js

Vue.js uses their own template syntax which you can learn more from https://vuejs.org/v2/guide/syntax.html

<div id="root">    
  <my-counter :value="counter"></my-counter>
  <my-button :callback="incrementCounter"></my-button>
</div>

Vue.js template syntax separates HTML code (UI) from JavaScript code

Vue.component('my-counter', {
  template: `<h2 v-html="value"></h2>`,
  props: {
    value: 0,
  },
  data() {    
  },
});

Vue.component('my-button', {
  template: `<button @click="callback">Click</button>`,
  props: {
    callback: null,
  },  
});

var app = new Vue({
  el: "#root",
  data: {
    counter: 42,
  },
  methods: {
    incrementCounter() {
      this.counter = this.counter + 1;
    }
  }
 });

See the Pen Click Counter – Vue by John Pili (@johnpili) on CodePen.

I hope this helps developers with their quest to learn both frameworks. In the next post, I will be demonstrating the iteration of components in React and Vue.js. Cheers!

Leave a Reply