If you know jQuery, you should switch to React

React

jQuery

a SWAT.JS talk

by Divi Bhatnagar and Alex Voerman

2007

Browser Wars

jQuery was AWESOME

Simple Setup


$(document).ready(function () {
    $('#hello-world').click(function () {
        // MAGIC!
    });
});

<head>
  <script src="./jquery-1.2.1.js"></script>
</head>

Simple API


var contactName = $('.contact-name').val();

$('.header-text').append('WELCOME, ' + contactName);

Ajax



$('.pump-dat-data').click(function() {
    $.ajax({
        url: 'ajax/table.html',
        type: 'GET',
        success: function(res) {
            $('.results-table').html(res);
        }
    });
})
var sum;

$.each([1, 2, 'poop'], function() {
   sum += $.isNumeric(this) ? this : 0;
});


var nameToSend = $.trim(nameInput);


var newObject = $.extend(obj1, obj2);

Utilities / Browser Compatibility

this.$outerDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass('text')
    );

$(window).resize(function() {
   fixIe();
})

$('.my-container > .nav-container > .nav > .red button').click(function () {
    // logic  
});

$('.my-container > .nav-container > .nav > .blue button').click(function () {
    // logic  ?
});

// DONT TOUCH THIS
$('.my-container > .nav-container > .nav > .green button').click(function () {
    // logic  ? ? ?
});


// HACK FOR IE6
$('#results-form-element').change(function () {
    // logic  
});

???

2015

var toppingsList = [
    'mushrooms', 'cheese', 'peppers'
];


var result = '';
$.each(toppingsList, function(index) {
    var toppping = this.toUpperCase();
    
    result += toppping;
    if (index !== toppingsList.length - 1) {
        result += ', ';
    }
});
const toppingsList = [
    'mushrooms', 'cheese', 'peppers'
];


const result = toppingsList
    .map(res => res.toUpperCase())
    .join(', ');

Use ES2015+ for Utility Methods

jQuery

ES2015+

$.ajax({
    url: 'https://my-api.com/data',
    type: 'GET',
    success: function(res) {
        console.log(res);
    },
    error: function(err) {
        console.error(err);
    }
});
fetch('https://my-api.com/data')
  .then(res => console.log(res))
  .catch(err => console.error(err))

Use Fetch instead of $.ajax

jQuery

ES6+

//file.js
$('.my-button').click(function(e) {
  e.preventDefault();
  console.log('this is:', e.target);
});
class App extends React.Component {
  handleClick = (e) => {
    e.preventDefault();
    console.log('this is:', e.target);
  };

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

Click Handler

jQuery

React

<!-- file.html -->
<button class="my-button">
  Click me
</button>
<!-- file.html -->

<div id="app">
  <button class="my-button">Toggle me</button>
  <p class="toggle">Change Color</p>
</div>
class App extends React.Component {
  state = { toggled: false };

  handleClick = (e) => {
    e.preventDefault();
    this.setState({ toggled: !this.state.toggled });
  };

  render() {
    const toggleClass = this.state.toggled
                        ? 'red' : '';
    return (
      <div>
        <button
          onClick={handleClick}>Toggle Me</button>
        <p className={toggleClass}>Change Color</div>
      </div>
    );
  }
}

Toggle Class

jQuery

React

// file.js
var classToggled = false;

$('my-button').click(function(e) {
  if (classToggled) {
    $('.toggle').addClass('red');
  } else {
    $('.toggle').removeClass('red');
  }
});
<!-- file.html -->
<div>


  <input class="my-name" type="text" />


  <div class="greeting"></div>

</div>
class App extends React.Component {
  state = { name: '' };

  handleChange = e => {
    this.setState({ name: e.target.value });
  };

  render() {
    return (
      <div>

        <input
          value={this.state.name}
          onChange={this.handleChange}
        />
        <div>{this.state.name}</div>

      </div>
    );
  }
}

Input & Output

jQuery

React

// file.js
var name = '';
$('.my-name').keyUp(function(e) {
    name = $(this).val();
    $('.greeting').append(name);
});

Breaking things into components

EXAMPLE

Create-React-App

Reference

 

Getting started with React:

    > npx create-react-app my-app
    > cd my-app
    > npm start

From jQuery to React

By Alex Voerman

From jQuery to React

  • 99