Buy

JavaScript for PHP Geeks: ReactJS (with Symfony)

0%
Buy

The World of React + ESLint

Hey friends! And welcome! Oh, I am so excited to talk about React. Developing in React feels great, and it's powerful! You can build any crazy frontend you want. But, honestly, writing this tutorial was a huge pain. Technically speaking, React is not hard. But, to even get started, you need to be comfortable with ES6 features and you need a build system, like Webpack Encore. That's why we covered both of those topics in previous tutorials.

But even then! The best practices around React are basically non-existent, especially for a backend developer, who instead of building a single page app, may just want to use React to power part of their frontend.

So our goal in this tutorial is clear: to master React, but also learn repeatable patterns you can follow to write high-quality code while getting your wonderful new app finished, and out the door. We won't hide anything: we'll attack the ugliest stuff and, as always, build something real.

Excited? Me too! And, a huge thanks to my co-author on this tutorial Frank de Jonge, who helped me navigate many of these important topics.

Project Setup

If you'd like free high-fives from Frank... or if you want to get the most out of this tutorial, you should totally code along with me. Download the course code from this page. When you unzip it, you'll find a start/ directory inside that holds the same code that you see here. Open up the README.md file for winning lottery numbers and instructions on how to get the project setup.

The last steps will be to open a terminal, move into the project, and run:

php bin/console server:run

to start the built-in web server. Our project already uses Webpack Encore to compile its CSS and JS files. If you're new to Webpack or Encore, go watch our tutorial on that first.

To build those assets, pour some coffee, open a second terminal tab, and run:

yarn install

to download our Node dependencies. And... once that finishes:

yarn run encore dev --watch

That will build our assets, and rebuild when we change files.

Ok cool! Let's go check out the app: find your browser, go to http://localhost:8000 and say hello to the Lift Stuff App! Login with user ron_furgandy password pumpup.

In our effort to stay in shape... while sitting down and coding all day... we've built Lift Stuff: an app where we can record all the stuff we've lifted throughout the day. For example, before I started recording, I lifted my big fat cat 10 times... so let's totally log that!

In the previous tutorials, we built this JavaScript frontend using plain JavaScript and jQuery. In this tutorial, we'll re-build it with React.

Installing ESLint

But before we dive into React, I want to install another library that will make life much more interesting. Move back to your terminal, open a third terminal tab - we're getting greedy - and run:

yarn add eslint --dev

ESLint is a library that can detect coding standard violations in your JavaScript. We have similar tools in PHP, like PHP-CS-Fixer. To configure exactly which coding standard rules we want to follow, back in our editor, create a new file at the root of the project: .eslintrc.js.

I'll paste in some basic configuration here: you can copy this from the code block on this page. We won't talk about ESLint in detail, but this basically imports the ESLint recommended settings with a couple of tweaks. This jsx part is something we'll see very soon in React.

20 lines .eslintrc.js
module.exports = {
extends: ['eslint:recommended'],
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
jsx: true
}
},
env: {
browser: true,
es6: true,
node: true
},
rules: {
"no-console": 0,
"no-unused-vars": 0
}
};

Thanks to this, we can now run a utility to check our code:

./node_modules/.bin/eslint assets

where assets/ is the directory that holds our existing JavaScript code. And... aw, boring! It looks like all of our code already follows the rules.

This utility is nice... but there's a more important reason we installed it. In PhpStorm, open the settings and search for eslint to find an ESLint section. Click to Enable this and hit Ok. Yep, PhpStorm will now instantly tell us when we've written code that violates our rules.

Check this out: open assets/js/rep_log.js: this is the file that runs our existing LiftStuff frontend. Here, add const foo = true then if (foo), but leave the body of the if statement empty. See that little red error? That comes from ESLint.

This may not seem very important, but it's going to be super helpful with React.

Adding a new Entry

As I mentioned, our app is already built in normal JavaScript. Instead of deleting our old code immediately, let's leave it here and build our React version right next to it. In the same directory as rep_log.js, which holds the old code, create a new file: rep_log_react.js. Log a top-secret, important message inside so that we can see if it's working. Don't forget the Emoji!

console.log('Oh hallo React peeps! 🏋️');

Now, open webpack.config.js: we're going to configure this as a new "entry". Typically, you have one entry file per page, and that file holds all of the JavaScript you need for that page. Use addEntry('rep_log_react') pointing to that file: ./assets/js/rep_log_react.js.

... lines 1 - 3
Encore
... lines 5 - 12
.addEntry('rep_log_react', './assets/js/rep_log_react.js')
... lines 14 - 28
;
... lines 30 - 33

To build this, go back to your terminal, find the tab that is running Webpack Encore, press Ctrl+C to stop it, and run it again: you need to restart Webpack whenever you change its config file.

Finally, to add the new JavaScript file to our page, open templates/lift/index.html.twig, find the javascripts block, and add the script tag for rep_log_react.js. You don't normally want two entry files on the same page like this. But when we finish, I plan to delete the old rep_log.js file.

And just like that, we can find our browser, open the dev tools, go to the console, refresh and... Hello World!

Now, it's time to go say Hello to React!

Leave a comment!

  • 2018-10-01 Shaun

    Thanks for the clarification weaverryan :)

  • 2018-09-17 weaverryan

    Hey Shaun!

    You can ignore these :). This is a little incompatibility with how npm packages work and how Webpack Encore works. In Encore, we require webpack as a dependency so that YOU don't have to. But, this means that you get these above warnings. They're not actually a problem, as these libraries will just use the Webpack provided by Encore internally, but they are annoying, and confusing. We may change Encore in the future to require *you* to install Webpack to avoid these - I'm not sure - something I think about :).

    Cheers!

  • 2018-09-17 Shaun

    I have added ESLint, but I get the following warning:

    [3/4] 🔗 Linking dependencies...
    warning " > babel-loader@7.1.5" has unmet peer dependency "webpack@2 || 3 || 4".
    warning " > sass-loader@6.0.7" has unmet peer dependency "webpack@^2.0.0 || ^3.0.0 || ^4.0.0".

    But I already have Webpack installed?

  • 2018-09-07 Mark Railton

    No worries weaverryan, this course is looking like exactly what I was looking for. Gonna start in on it properly once other things settle a little.

  • 2018-09-06 weaverryan

    Hey Mark Railton!

    Ah, thanks for the ping on that! I'll update that right now - we had the same issue on our Symfony series :).

    Cheers!

  • 2018-09-06 Mark Railton

    Heads up for people starting the course, seems that the version of flex used is out of date, was getting an error when trying to run composer install in the start dir - Declaration of Symfony\Flex\ParallelDownloader::getRemoteContents($originUrl, $fileUrl, $context) should be compatible with Composer\Util\RemoteFilesystem::getRemoteContents($originUrl, $fileUrl, $context, ?array &$responseHeaders = NULL) - seems you need to run composer update to get the dependencies to install

  • 2018-08-27 Victor Bocharsky

    Hey James,

    In simple words, why React over jQuery: The more you need to change after some events, like after you sent an AJAX request and got a response with some data that you need to update on the page - the more you need to look into React JS direction :)

    But if you want an example, try to finish this ReactJS course, I bet you will understand better ReactJS in the end of this tutorial and it will be more obvious for you when ReactJS is better than jQuery.

    Cheers!

  • 2018-08-24 James Davison

    Thanks Ryan for this AWESOME answer, I can't seem to really understand why exactly we would need to use React? Have you got some example where you believe you would absolutely use React over just simple javascript like jQuery?

    Thanks again for your time!

  • 2018-08-24 weaverryan

    Hey James Davison!

    That's a very interesting application! :). There are 2 parts to this answer:

    1) React? Maybe! It's not that complex of an app from a JavaScript standpoint. Though, you may not be telling me all the details. The more complex the number of interactions, the more React makes sense. So, it's sort of up to you. For a simple app like this, it will take you *longer* in React, because you'll need to learn React as you go versus using tools you already know (e.g. jQuery). But if you *want* to learn and aren't on a tight deadline, it's a simple app and so a pretty good candidate for learning.

    2) The *real* unique thing about your app is how you need one user's screen to change when *another* use performs some action. There are 2 ways to solve this. First, the traditional, but ugly way: When a user clicks "New round", you make an AJAX request to the server to set some new database value. Then, all the users from his/her group make "polling" AJAX requests to *check* to see if there is a new round that was created. This solution isn't ideal, because it literally means that every user needs to *constantly* make AJAX requests to ask "Is there a new round?". To make the app feel "responsive" you might need to make these every 5 seconds. Bummer!

    What's the *second* way to solve this? Web sockets! In this setup, when he/she clicks "New round", you would probably *still* send an AJAX request to the server to update some stuff in the database. But then, you would be able to push this notification from the server *directly* to the JavaScript of the users in his/her group so that the know of the new round immediately. The best way to do this in PHP (and I love this service) is with Pusher: https://pusher.com/. They allow you to have this setup with *very* little setup work. We use it here on our coding challenges: when you submit a new challenge, we notify you immediately (via Pusher) when the "grading" is finished.

    I hope this helps!

    Cheers!

  • 2018-08-23 James Davison

    Hi Guys,

    I am looking to use Reactjs but I am not sure if it is really the solution to my problem.

    I am looking to create a Tea app.

    When a user wants a tea, here is the "New round process":

    1. He/She clicks on "New round"
    2. All users from his/her group are notified that a new round is on the go
    3. These users see their page to change (without reload), to ask them if they want a cup of tea
    4. These users select YES or NO and press "Yes I want a cup of tea"
    5. After 5 min these users see their page to change (even if they selected NO) to display who wants a cup of tea and who has been chosen to make it

    Do you think Reactjs is the right way to go?

  • 2018-06-21 Dan Meigs

    I'm using 2018.1.

  • 2018-06-20 Diego Aguiar

    Interesting... what PHPStorm version are you using?

  • 2018-06-20 Dan Meigs

    Hey guys!

    Glad to get started on this tutorial. When I installed eslint and enabled the plugin, PHPStorm complained that I didn't have eslint-plugin-react. I had to add that with yarn to get the PHPStorm plugin to work.

    Cheers!

  • 2018-06-19 weaverryan

    Hey Lopoi Popoi!

    Great question! We didn't mean to be so mysterious :). We have an entire JavaScript track: https://knpuniversity.com/t...

    We built this application in the first 4 tutorials of this track. The really important ones are:

    1) JavaScript for PHP Geeks: https://knpuniversity.com/s...
    2) ES6 https://knpuniversity.com/s...
    3) Webpack Encore: https://knpuniversity.com/s...

    If you're new to ES6 or Webpack, you will NOT regret going through these tutorials :).

    Cheers!

  • 2018-06-19 Lopoi Popoi

    Hi KNP team!

    What is the base (plain JS?) tutorial you are refer to in this React one as a base?