Pixies, part 4: A Bit of React


ES6

ES6(ECMAScript 6) is the latest standard of the Javascript language. It has much cleaned, modernized syntax. It is less confusing from the people coming from other environments and, generally, a pleasure to work with. There is on problem though If you write your app with ES6, there is no guarantee that it will work on all (especially old) browsers. The community came up with Babel, a javascript “compiler” which takes modern Javascript, like ES6 and produces the classical javascript which should be consumed by all, even old browser. Of course, one can automate that with the Webpack.

npm install babel-loader @babel/core @babel/preset-env @babel/preset-react --save-dev

Once it installed, modify your webpack.config.js, add the following rule to let babel process your js files:

//... as before
rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
// ... as before

React allows you to create and use components, independent and reusable pieces of the Javascript code. So let’s build one

Our first React component

Install React and create an empty file in the src directory:

npm install react react-dom --save-dev
touch src/App.js

Make the App.js look like this:

import React from 'react';

const App = () => {
  return <h1>React Pixies</h1>;
};

export default App;

As you see, on the surface,the component is just a Javascript function which returns a chunk of html. But wait a minute, how one can intermix together html tags directly with the Javascript code? The short answer is that utilizing this, so called jsx syntax, React are able to convert this to the pure javascript which, essentially produces the desired html elements. This is very nice, because you are not forced to jump between javascript and html code and keep everything together.

Next, in order to enable React in your application, in your index.html file you need to create a special element which will served as the root of your React app. Replace the body tag of your src/index.html with this:

<body>
  <section id="root"></section>
</body>

Ok, we have our index.html ready for React, now let’s actually enable it in the index.js and use our new component there:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(<App />, document.querySelector('#root'));

As you see, we ask React to render your our App component in place of the html element with id root.

Start the app:

npm start

You will see that app looks pretty much the same but the text on the web page comes from the React, not hardcoded into index.html as before

Great thing about the React is that not only we can use components which we have written, but also chose ones from the variety of the open source libraries. We are going to use the image carousel component from the React Bootstrap library. Let’s install it:

npm install react-bootstrap --save-dev

We are going to display a couple of images in the carousel, For the purpose of this tutorial, we are going to use some nature photography images made by Dasha Gudalewicz. You can use your own if you wish. Each image will be represented by a javascript object with three fields, url, caption and details. Create the array of these objects in your App.js, just above the return statement:

  const items = [
  {
    url:
      'https://photos.smugmug.com/Animals/Birds/Warblers/Yellow-Warbler-2013/i-Tr5rQBN/0/f058a66f/X5/191130_Camino%20de%20grava%20entre%20el%20Corchito%20y%20Estero%20de%20Chicxulub_079-X5.jpg',
    caption: 'image 1',
    details: 'details 1'
  },
  {
    url:
      'https://photos.smugmug.com/Animals/Reptiles/Crocodilians/American-Crocodile/i-vkN5pCN/0/b92acda4/5K/151029_Everglades_729-5K.jpg',
    caption: 'Image 2',
    details: 'details 2'
  },
  {
    url:
      'https://photos.smugmug.com/Animals/Reptiles/Lizards/Pygmy-Horned-Lizard-2013/i-cdRKpxK/0/fe991315/X5/131005_ManastashRidge_693-X5.jpg',
    caption: 'Image 3',
    details: 'details 3'
  }
  ];
                    ];

Import the Carousel component from the React Bootstrap library, at the top of your App.js:

import React from 'react';
import { Carousel } from 'react-bootstrap';

Let’s return the Carousel populated with the our images. Instead of our current placeholder

return <h1>React Pixies</h1>;

Enter the code like this:

return (
    <div className='container'>
      <div className='row'>
        <Carousel>
          {items.map(item => (
            <Carousel.Item>
              <img className='d-block w-100' src={item.url} alt='' />
              <Carousel.Caption>
                <h3>{item.caption}</h3>
                <p>{item.details}</p>
              </Carousel.Caption>
            </Carousel.Item>
          ))}
        </Carousel>
      </div>
    </div>
  );

This probably requires some explanation. As before, we are still using jsx syntax to inject html directly to the javascript. Things to notice:

  • As this is, technically, still javascript, you cannot use javascript reserved keywords like class React recognizes the className and will convert to proper html class attribute when emitting actual html.
  • html in jsx also can use javascript code, in such cases it has to be wrapped in the curly braces. javascript inside html while inside javascript - got that?
  • the code simply loops over our items array and emits the <Carousel.Item> component configured with the data from our image objects.
  • there are Bootstrap attributes sprinkled here and there. If you don’t know Bootstrap, don’t worry about this.

Run the app

npm start

And you will see that the image carousel is populated with three images.

If you are following along, now it is a good time to check in


git add -A
git commit -m "Bootstrap React carousel"

and deploy the updated version to Heroku:


heroku container:rm web
heroku container:push web
heroku container:release web

When you open your live app

heroku open

you will see your app now shows some images.

Next, we are going to build the backend which stores the data about the images in the database so our frontend can fetch it from there. As Heroku provides the PostgreSQL database for us, in the next module we are going to talk about how to set the PostgreSQL for the development on our machine.


See also