Posts on this Category



How to Set up a Database connection with ReactJS

The short answer to this question is: You shouldn’t use React to connect directly to your database. React is a front-end framework, it should only be responsible for the user interface. If you need a database connection, the right place for it is the back-end, that’s also where you’re going to fetch and process the data before you provide it to the presentation layer.

Now let me show you how to do that. In this example I’m using PosqgreSQL database and Node.js with Express on the server-side.

const express = require('express')
const app = express()
const { Pool, Client } = require('pg')
const pool = new Pool({
   user: 'postgres',
   host: 'localhost',
   database: 'db',
   password: 'pw',
   port: 5432,
})
 
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});
 
app.get('/data', (req, res1) => {
      pool.query('SELECT id, description FROM products', (err, res) =>{
      if (err) {
	 console.log(err.stack)
      } else {
         res1.send(res.rows)
      }
   })
})
 
app.listen(3001);
 
module.exports = app;

This is the simplest possible example on how to connect and execute queries. I’ve used the node-postgres module to be able to interact with PostgreSQL, so don’t forget to install it on your NodeJS project.

Since you’re here because of React, I don’t want to get into details about NodeJS in this post, and as far as I know, lots of you aren’t even using NodeJS in the back-end. So all we need to know here is that our node application will provide data from the database via the following link: http://localhost:3001/data. Now let’s see how to use this link on the React project.

import React, { Component } from 'react';
import './App.css';
 
class App extends Component {
 
  constructor() {
      super();
      this.loadData();      
  }
 
  loadData(){
    this.state = { data: [] };
    fetch('http://localhost:3001/data') 
      .then(result=>result.json())
      .then(data=>this.setState({data}));
  }
 
  render() {
    return (
      <ul>
        {this.state.data.map(item=><li>{item.id} - {item.description}</li>)}
      </ul>
    );
  }
}
 
export default App;

In this example we have a very simple React component. Take a look at the loadData method, that’s where we are getting the data from the server. I’m using the fetch API to make the request, so all we have to do is provide the link and it will return the data for us. When it receives the response I’m storing the result in the local state so I can access it from the render method and present it as I like, in this case I’m showing the data as a list.

That’s it guys!! Hope you liked the tutorial, I tried to keep this post simple, so maybe it wasn’t as detailed as you expected, but if you have any doubts please don’t hesitate to ask, just leave a comment and I’ll do everything I can to help you.

How to use Bootstrap in a Reactjs project

Styling is a little bit different in Reactjs, so you cannot use Bootstrap in a traditional way. In this tutorial I’m going to show you an easy way to add Bootstrap to a Reacjs project. As we can’t use the traditional Bootstrap we have to use another version called React-Bootstrap, it’s basically the same framework, but it was rebuilt so we can use it with React. You can install it in your project via:

npm install --save react-bootstrap

React-bootstrap doesn’t come with the CSS, so you have to add it manually to your index.html:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">

Ok, we’re already done with the setup. Now we’re ready to import the components and start using them. To give you an example of how to do that I’m going to import the Bootstrap FormControl component and use it in my project.

import React, { Component } from 'react';
import FormControl from '../node_modules/react-bootstrap/lib/FormControl';
 
class Field extends Component {
  render() {
    return (
        <FormControl type="text"/> //<-- This is equivalent to <input class="form-control" type="text"/>
    );
  }

Note that in line 2 I’m importing the FromControl from the react-bootstrap folder inside the node_modules. I recommend you to check this folder so you can see all the components you have available. If you run your project now you’ll see the bootstrap input you’re used to.

That’s pretty much it, of course not every react-boostrap component will be as simple as this one, so if you have any doubts on how to use them please let me know in the comments.

Reacjs Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + ’em’}} when using JSX

This error occurs when you try to pass regular CSS strings to the style attribute of an HTML element. In React, the styling is different, instead of an string the style attribute expects an object.

So instead of doing this:

<p style="font-size: 12px; color: black" >text</p>

you should do this:

var pStyle {
   fontSize: '12px',
   color: 'black',
};
<p style={pStyle} >text</p>

Note that the name of some CSS attributes are a little bit different in React, you should always write them camelCased. As you can see in this example the font-size attribute became fontSize.

That’s pretty much it! Hope it helps.

Reactjs Error: Adjacent JSX elements must be wrapped in an enclosing tag

This is a very common Reactjs error, specially for beginners. If you are getting this error you code probably looks like this:

class App extends Component {
  render() {
    return (
        <Component1></Component1>
        <Component2></Component2>
    );
  }
}

The problem is that your render function is returning two elements, it’s equivalent to adding two return statements to your function, and reactjs won’t allow that.

The solution is very simple, you just have to add an enclosing tag as described in the error message. After this modification the code should look like this:

class App extends Component {
  render() {
    return (
      <div>
        <Component1></Component1>
        <Component2></Component2>
      </div>
    );
  }
}

As you can see I’ve added a div as an enclosing tag, now the function is returning only one element. This this should fix the problem, but if it doesn’t please let me know in the comments.

How to load a JSON file in Reactjs

It’s really easy to load data from a JSON file in React. In this post I’m going to show you how you can do that. First, of course, we need a JSON file, you probably already have yours, but I’m using this movies list for this example:

data.json

[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Now we have to place this file somewhere inside our project folder, it doesn’t necessarily need to be on the project, but it must be somewhere accessible via Http.

Once you have the path to your file you can load it this way:

import React, { Component } from 'react';
import data from './data.json';
 
class App extends Component {
  render() {
    return (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}
 
export default App;

Note that all I had to do was to import the file in line 2, then the data was already ready for me to use on the data variable. Lastly, to show you how to use this variable I’ve made this component iterate over the dataset and display it on a list.

Easy right! If you have any doubts please let me know in the comments.

Getting Started with Facebook’s React and Flux

reactjs flux
ReactJS Homepage

React and Flux are two of the most promising technologies of the present days, both are constantly showing up on trending technologies lists, quickly gaining market and becoming popular among developers. The first one defines itself as an open source javascript library for building user interfaces, it is an excellent tool for developers to create highly dynamic UI components, as the second is a brand new application architecture for client-side web apps designed to work together with React by using unidirectional data flow.

Let’s start by talking a little bit more about React with an example, and later on I’ll give more details about Flux and apply it to the first example.

Creating our first Application with React

The example bellow is a classic Hello World example using react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
   <head>
	   <title>React Flux</title>
   	   <script src="https://fb.me/react-0.13.3.js"></script>
  	   <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
 
 	   <script type="text/jsx">
		   var HelloWorld = React.createClass({
		     render: function() {
		       return <div>Hello World!!</div>;
		     }
		   });
 
		   React.render(<HelloWorld />, document.getElementById('component'));
 
	   </script>
   </body>
</html>

If you carefully analyze the code, the first different thing you should notice is the new script type text/jsx, which is basically Javascript with some HTML elements.

You can also see that I had to add three scripts to my page, the first and the second are the React and JSX scripts respectively, and the third one is jQuery, I’ll explain in a moment why we need it.

Now let’s analyze the code and see how it works, take a look at the declaration of HelloWorld var, this is the variable that will actually hold our new component. In React we always have to create the specification of our components through the function React.createClass, it receives an object as a parameter containing a render function, this function will process and return the component’s HTML code the way it’ll be displayed on the browser, in this example I’m just returning a div with a text within it, nothing dynamic for now.

After implementing our component we need just one more line of code to make it appear on the page, to show it we have to call React.render (line 19 of the example), this function receives two parameters, the first one is the component that will be displayed and the second one is where we want to display it, this is where JQuery will come into action, note that right after the body declaration we have a div with the id=component, I’m using JQuery’s getElementById to get this div and render my HelloWorld component on its place. Now if you run this application you should see ‘Hello World!!’ on your page.

Using Flux Architecture

flux architecture
Flux Homepage

As I said before Flux is a new architecture used by Facebook that complements React components by using unidirectional data flow, it is divided in four parts: the dispatcher, stores, views and controller-views. Every action, no matter where it comes from, is received by the dispatcher which will be responsible for changing the state of the appropriate store, after the state is modified it will notify the controller-view that will retrieve the new data and update all its child views.

Here is as brief explanation for each one of the components:

Dispacher – Is the central component that manages the data flow within the application, it distribute the actions to the appropriate stores.
Store – Components that contains the logic and state of the application.
View – The components that represent the user interface.
Controller-view – The type o view the listens to events coming from the stores.

It may be hard to understand at first but once you see an example it will get easier. To illustrate how this architecture works I’m going to use the same preview example but slightly modified just enough to demonstrate how Flux works, so instead of just showing ‘Hello World!!’ on the page we’re going to render a button that will trigger an action and show the hello world message, the difference is that now we have an action involved.

First we’re going to move our react code to another file that, it’ll be called HelloWorld.jsx, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
var React = require('react');
var HelloWorldAction = require('../Actions/HelloWorldAction.js');
 
var HelloWorld = React.createClass({
	showMessage:function(){
		HelloWorldAction.showMessage('Hello World!!');
	},
	render: function() {
		return <a onClick={this.showMessage}>Click Here</a>;
	}
});
 
module.exports = HelloWorld;

I’ve already made the changes, now I’m rendering a link that when clicked will trigger the showMessage function and pass our message to HelloWorldAction, which will be responsible to delivery it to the dispatcher, here is the HelloWorldAction code:

1
2
3
4
5
6
7
8
9
10
11
12
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
 
var HelloWorldAction = {
	showMessage:function(message){
		Dispatcher.handleViewAction({
			actionType:'SHOW_MESSAGE',
			message:message
		});
	}
}
 
module.exports = HelloWorldAction;

Here I’m just wrapping my message that in this case will be my payload, and I’m also assigning an actionType to it, then I’m passing this action to the dispatcher:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');
 
var AppDispatcher = assign(new Dispatcher(),{
	handleViewAction:function(action){
		this.dispatch({
			source:'VIEW_ACTION',
			action:action
		});
	}
});
 
module.exports = AppDispatcher;

This is the dispatcher code, here we have the implementation of the handleViewAction function that is receiving the payload from the HelloWorldAction, the purpose of this is to broadcast it to the stores, then the appropriate store can perform the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
 
var AppStore = assign({},EventEmitter.prototype,{
	emitChange:function(){
		this.emit('change');
	}
});
 
AppDispatcher.register(function(payload){
	alert(payload);
});
 
module.exports = AppStore;

Lastly we have our store, here I’m implementing and registering in the dispatcher the method that will actually show the message.

That’s it, now before you run it, since we used jsx code, you have to use browserify and reactify to compile it.

I know I didn’t give too much details on this tutorial, this application is so simple that it’s kind of weird to write that much code just to show a hello world message, I’m looking forward to write another post with a more complex application, this way we can explore react and flux a little further.