Diving into ReactJS

March 22, 2018

The minimalist guide to getting started with React.

Personally, when I trying to learn a new language / framework I like to have basic playground running that would let me play around with code snippet, making and breaking stuff as I learn about it. Having this playground ready for React is a cumbersome task. One has to fight with webpack and babel configs. Often times copy pasting code from the tutorials – we end up missing a comma or a quote and are left wondering "WTF why does it not work ?"

React minus the config

Say hello to NextJS – a minimalistic framework for creating server-rendered React applications. Developed and maintained by the awesome guys at Zeit, it is the best way to get started with React.

It makes you focus on React and leave all the trouble of configuring webpack and babel to the experts.

Of course you can learn about the configs later on when you feel comfortable enough with React and want to customize it as per your needs but initially lets just focus on having your React playground ready where you can make and break stuff :-)

Lets begin

Moving forward I am going to assume you have a NodeJS environment ready and working.

1. Initialize an NodeJS app

In the terminal, navigate to an empty folder of your choice and execute the command to initialize a NodeJS app

npm init -y

2. Install NextJS and ReactJS

Intall the necessary module for our app, run the command

npm install --save next react react-dom

3. Setup scripts to run the app

Open package.json in an editor of your choice and add the following scripts block. If your package.json already has a scripts block, just replace it :-)

 "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }

4. Lets write React!

Would you believe if I told thats all the config you will need. We can now start writing React code

Create a folder pages within your project folder.

In that folder create a file index.js. Your project folder should look like the following.

project_folder
  |
  |–– package.json
  |–– package-lock.json
  |–– node_modules
  |–– pages
        |
        |–– index.js

4.1 First component

Open the index.js in the editor and copy - paste the following code and save.

import React, { Component } from "react";

class Index extends Component {
  render () {
    return (
      <div>Hello, world!</div>
    );
  }
}

export default Index

5. Browser time

Back in the terminal, run the command

npm run dev

The terminal will inform you that the app is running at http://localhost:3000. Open you browser to the said URL and voila!

You can see your first React component in action.

Conclusion

Thats it!. You have your ReactJS playground ready, you can now start focusing on learning the various concepts of React.

Moreover, this setup lets you write modern ES6 Javascript and comes built in with hot reloading – your browser will immediately reload after every change in index.js.

Happy hacking!