Dieses Blog durchsuchen

Sonntag, 28. August 2016

react.js: create a basic table component with bootstrap styles

Today we want to implement a simple task in HTML with css.
A Simple datatable like that:

The tablecomponent has a thead, a tbody and a stripe css set.

In good old html we do that like this:
<table class="table table-striped">
  <thead class="thead-default">
<tr>
    <th>ID</th>
    <th>Name</th>
   </tr>
</thead>
<tbody>
<tr>
  <td>1</td>
  <td>Nikko Laus1</td>
 </tr>
<tr>
  <td>2</td>
  <td>Sam Collins</td>
 </tr>
<tr>
  <td>3</td>
  <td>Carl Smith Wesson</td>
 </tr>
<tr>
  <td>4</td>
  <td>Peter Austin</td>
 </tr>
<tr>
  <td>5</td>
  <td>Tini Titus</td>
 </tr>
<tr>
  <td>6</td>
  <td>Sarra Cams</td>
 </tr>
</tbody>
</table>


Now we want to to this the react way.
We want to split the table in 3 components. One "App" component to wrap all other components. One TableRowComponent, which handles each row and a tablehead component to format the tablehead.

We are using Visual Studio code with all available react plugins on ubuntu 16.04

This tutorial is inspired by this great egghead video from Joe Maddalone:
https://egghead.io/lessons/react-dynamically-generated-components 

Prerequisits

At first, you need to have some tools installed. Here they are.
node.js installed
npm installed

babel react
the facebook react library

babel installed
Babel is a javascript compiler, which transforms latest javascriptstandards to native javascript

webpack installed
Webapck is a modulebundler which  creates statis js assets for the browser

Bootstrap installed
Bootstrap is a common css , component framework from twitter


$ apt-get install nodejs
$ apt-get install npm
$ npm install -g --save babel webpack webpack-server-dev
$ npm install --save babel-core babel- loader babel preset-es2015 babel-preset-react
$ npm install css-loader style-loader file-loader url-loader --save-dev
 

Init your node project

To initialise your project simple type:
$ npm init

This will create your package.json

Fill your projectdata 
My package.json looks like that
{
  "name": "react-redux",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.14.0",
    "babel-preset-react": "^6.11.1",
    "bootstrap": "^3.3.7",
    "react": "^15.3.1",
    "react-bootstrap": "^0.30.3",
    "react-dom": "^15.3.1",
    "webpack": "^1.13.2",
    "webpack-dev-server": "^1.15.0"
  },
  "devDependencies": {
    "css-loader": "^0.24.0",
    "file-loader": "^0.9.0",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7"
  }
}


Add your component files

Create a index.html 
This will contain your main html page

main.js
this will load your components

webpack.config.js 
this will setup your dependencies and loaders and defines the compilingprocess of es2015 babel to native javascript

App.js
Here you will code your components
touch main.js index.html App.js webpack.config.js 

Configure your webpack.config.js

Open your webpack.config.js and add folling code
module.exports=
{
    entry:'./main.js',
    output:
    {
        path:'./',
        filename: 'index.js'
    },
    devServer:
    {
        inline:true,
        port:3333
    },
    module:
    {
        loaders: [
            {
                test:/\.js$/,
                exclude: /node_modules/,
                loader:'babel-loader',
                query:
                {
                    presets:['es2015','react']
                }
            },
            { 
        test: /\.css$/, 
        loader: "style-loader!css-loader" 
      },
      { 
        test: /\.png$/, 
        loader: "url-loader?limit=100000" 
      },
      { 
        test: /\.jpg$/, 
        loader: "file-loader" 
      },
      {
        test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, 
        loader: 'url?limit=10000&mimetype=application/font-woff'
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, 
        loader: 'url?limit=10000&mimetype=application/octet-stream'
      },
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, 
        loader: 'file'
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, 
        loader: 'url?limit=10000&mimetype=image/svg+xml'
      }
        ]
    }
}
- This will tell webpack to pack a index.js with all javascripts in it
- Start a webserver on port 3333
- test all .js files
- Generate native javascript from babel sources.
- Tell webpack to load boostrap filetypes, mimetypes


Load your javascript on your html page

Open your index.html and add folling snippet
<!DOCTYPE html>
<html>

<head></head>

<body>
    <div id="app"></div>
    <script src="index.js"></script>
</body>

</html>

- This will add a div with id "app" which is the container for our app
- include the webpack generated index.js

Create your bootrap react component

Open your App.js and add folling snippet
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component
{
    constructor() 
    {
        super();
        this.state = {
            data:[
                {id:1, name:"Nikko Laus1"},
                {id:2, name:"Sam Collins"},
                {id:3, name:"Carl Smith Wesson"},
                {id:4, name:"Peter Austin"},
                {id:5, name:"Tini Titus"},
                {id:6, name:"Sarra Cams"}    
            ]
        }
    }
  
    render() {
        
        let rows = this.state.data.map(person =>
        {
            return <TableRow key={person.id} data={person}/>
        });

        return (<table className="table table-striped">
            <TableHead/>
                <tbody>{rows}</tbody>
            </table>
            );
    }
}

class TableHead extends React.Component
{
    constructor()
    {
        super();
    }

    render()
    {
         return (<thead className="thead-default">
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
        </thead>
        );
    }
}

class TableRow extends React.Component
{
    constructor()
    {
        super();
    }

    render()
    {
        return (<tr>
                    <td>{this.props.data.id}</td>
                    <td>{this.props.data.name}</td>
                </tr>
            );
    }
}

export default App

- This adds a the base App Component with a dataset constructed as a state property in the constructor.
- This will add your App Component. This component renders an HTML-table with a seperate <TableRow> and a separate <TableHead> component in boostrap style.
- It also adds a <TableRow> component, which handles the row pattern
- At the end it adds a <TableHead> component, which builds the header of the tablecomponent 

Load your component in main.js

Open your main.js and add folling snippet
import App from './App';
import Bootstrap from 'bootstrap/dist/css/bootstrap.css';
import React from 'react';

import ReactDOM from 'react-dom';

ReactDOM.render( 
    < App / > 
    , document.getElementById('app')
    );

- Import your App component, which you have prevoiusly created and render it to a div with the id 'app'

Start your server and test your app

Open a terminal and type:
npm start 

This will start your webserver on port 3333

Surf to localhost:3333

Thats it, you have created your first bootstrap table component with bootstrap

Nice isn't it?

Samstag, 27. August 2016

react.js: create your first react app with webpack and babel on es2015

Today we want to write our first react Hello world app. Before we can start, we have to setup out dev-enviroment.

We are using Visual Studio code with all available react plugins on ubuntu 16.04

This tutorial is inspired by this great egghead video:

Prerequisits

At first, you need to have some tools installed. Here they are.
node.js installed
npm installed

babel react
the facebook react library

babel installed
Babel is a javascript compiler, which transforms latest javascriptstandards to native javascript

webpack installed
Webapck is a modulebundler which  creates statis js assets for the browser

$ apt-get install nodejs
$ apt-get install npm
$ npm install -g --save babel webpack webpack-server-dev
$ npm install --save babel-core babel- loader babel preset-es2015 babel-preset-react

Init your node project

To initialise your project simple type:
$ npm init

This will create your package.json

Fill your projectdata 
My package.json looks like that
{
  "name": "simplecommand",
  "version": "1.0.0",
  "description": "a simple console command",
  "main": "createUser.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/pboethig/nodejs-lessons.git"
  },
  "keywords": [
    "nodejs",
    "command"
  ],
  "author": "pboethig",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/pboethig/nodejs-lessons/issues"
  },
  "homepage": "https://github.com/pboethig/nodejs-lessons#readme"
}

Add your component files

Create a index.html 
This will contain your main html page

main.js
this will load your components

webpack.config.js 
this will setup your dependencies and loaders and defines the compilingprocess of es2015 babel to native javascript

App.js
Here you will code your components
touch main.js index.html App.js webpack.config.js 

Configure your webpack.config.js

Open your webpack.config.js and add folling code
module.exports=
{
    entry:'./main.js',
    output:
    {
        path:'./',
        filename: 'index.js'
    },
    devServer:
    {
        inline:true,
        port:3333
    },
    module:
    {
        loaders: [
            {
                test:/\.js$/,
                exclude: /node_modules/,
                loader:'babel',
                query:
                {
                    presets:['es2015','react']
                }
            }
        ]
    }
}
- This will tell webpack to pack a index.js with all javascripts in it
- Start a webserver on port 3333
- test all .js files
- Generate native javascript from babel sources.


Load your javascript on your html page

Open your index.html and add folling snippet
<!DOCTYPE html>
<html>

<head></head>

<body>
    <div id="app"></div>
    <script src="index.js"></script>
</body>

</html>

- This will add a div with id "app" which is the container for our app
- include the webpack generated index.js

Create your first component

Open your App.js and add folling snippet
import React from 'react';
class App extends React.Component {
    render() {
        return <div> Hello World</div>
    }
}

export default App
- This will import the react library and add a class App which only renders a div with the text "Hello world"

Load your component in main.js

Open your main.js and add folling snippet
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render( < App / > , document.getElementById('app'));

- main.js is the startup file, you have configured in webpack.config.js
- This will import the react library
- Import your App component, which you have prevoiusly created
- Adds your App component to the "app" div in your html


Start your server and test your app

Open a terminal and type:
npm start 

This will start your webserver on port 3333

Surf to localhost:3333

Thats it, you have created your first simple react app.+

That's awesome !

Mittwoch, 24. August 2016

node.js: create a console command without shell scriptig on ubuntu

Shellscripting for some simple commands are the 90ies. Today we want to setup a console command without any shell scripting. Only with javascript

Prerequisits

At first, you need to have some tools installed. Here they are.
node.js installed
npm installed
$ apt-get install nodejs
$ apt-get install npm

Init your node project

To initialise your project simple type:
$ npm init

This will create your package.json

Fill your projectdata 
My package.json looks like that
{
  "name": "simplecommand",
  "version": "1.0.0",
  "description": "a simple console command",
  "main": "createUser.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/pboethig/nodejs-lessons.git"
  },
  "keywords": [
    "nodejs",
    "command"
  ],
  "author": "pboethig",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/pboethig/nodejs-lessons/issues"
  },
  "homepage": "https://github.com/pboethig/nodejs-lessons#readme"
}

Add you command script

Get you node.js path
which node
This could output:
/usr/bin/node

Create a file "createUser.js" and add the shebang to it
!#/usr/bin/env node 
This will tell the system to use node.js to execute your script

Make your script executable
chmod a+x createUser.js


Tell npm to install your command
Edit your package.json and add the bin object
{
  "name": "simplecommand",
  "version": "1.0.0",
  "description": "a simple console command",
  "main": "createUser.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/pboethig/nodejs-lessons.git"
  },
  "keywords": [
    "nodejs",
    "command"
  ],
  "author": "pboethig",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/pboethig/nodejs-lessons/issues"
  },

 "bin": {
      "createUser": "createUser.js"
    },
"homepage": "https://github.com/pboethig/nodejs-lessons#readme"


Everytime you modifiý your command, you have to run the global installer
npm install -g

Install commander

To get your command running, we need the commander library, wich does the whole parsing thing for us,
npm install --save commander

Add you command code to the scriptfile

Open your createUser.js and add a simple command
#!/usr/bin/env node

var program = require('commander');

program
    .version('0.0.1')
    .usage('<username>')
    .parse(process.argv);

if(!program.args.length) {
    program.help();
} else {
    console.log('Username: ' + program.args);   
}

As you can see, we are requiring  the commander lib, add an option "username" and parse the input on the terminal.

If no argument was set, we display the helpfile.

If the username was given, we are outputting the username. And we succeed

Instead of that simple sample, you can implement your complex logic here.

That's it. Now you can run your command after you have installed your final scriptversion
 
$ npm install -g createUser.js 
$ createUser


This will output the helpfile of your new command. Nice !


Dienstag, 23. August 2016

Symfony3: create a console command and test it

Sometimes you need an easy way to create a console command to add some automation and some admintools to your application. With Symfony3 it is rediculous simple

Install symfony3

Open a console and execute:
$ composer require symfony/symfony

Create a project

Create a project "consoletest" by executing following command on the terminal
$ symfony new consoletest.

Now you have a new project created.

Add your command

Create a file "CreateUserCommand.php" on folder "src/AppBundle/Command" and add following Code
As you can see, this simple command extends from Class Command and implements only 2 methods.
The configure command sets up the command, setup name, description and , prints out helptexts if you want

The execute method does the final work and runs your commandcode. You can manipulate databases, filesystems, get a servicereponse or configure your application with it.

Run your command

At next you can test your command by typing :
$ bin/console app:create-user

You should see your helptext,



Awsome. Isn´t it?

Create a unittest for your command

With symfony it´s very easy to test your new command. Here is a simple test for it:
- Create a folder and a file "test/Appbundle/CreateUserCommandTest.php" with following content in it

And now you can run
$ phpunit symfony

Montag, 22. August 2016

ES6: prevent that = this;

Some days ago I found a solution for following problem in Javascript:

Solve a really ugly problem

I know many lines of code where you find follwing that-this reference
Now with ES6 you can solve this problem with the arrow function like this.

As you can see, you can directly use this in the arrow-function, which is a kind of a shortcut to "function". Thats really nice.

Sonntag, 21. August 2016

node.js: create a contactform with express, jade, boostrap and node-mailer

Today we want to create a contactform and send a message via gmail.
To make the form look good, we add bootstrap to hour project and we are using express to setup the webserver. At the end we want to use node-mailer to send the email. This might sound complicated, but you only have to follow my copy & paste instructions and everythings will be easy.

Prerequisits

At first you need to have some tools installed. here they are.
This should be familliar to you

node.js installed
npm installed
a gmail account with username and passsword
Installed and working express. For that please follow the last tutorial >>here<<.

After that, you have express installed, jade added to express and a routing added

Add the jade contactform

Jade is a templatelanguage like jsx, phptal, velocity etc. There are some facts, which seems to be nice, like the shortened syntax. But there might be some contras against jade too. For now we want to be open for new technologies and give jade a try.

If you want to get more information about jade, visit: http://jade-lang.com/

Create a file named "contact.jade" to your views folder. If you do not have a views folder, create one in your projectfolder and place following code to the contact.jade file.


Create the routes for your form

Open your app.js and add the contact-routes.(See comments in following code).
One route to render the form, and one route to send the email. My complete app.js looks like that

This will bind a route "contact" and "contact/send" to your express webserver app. the simple "contact" route only renders the form.

The more complex route "contact/send" will do a lot of stuff more. At first, it will create a transporter object, which tells the mailer to send the email via googles gmail over a predefined "from account". After that, it defines the mailoptions with the plaintextversion, the htmlversion, the sender and the recipient

At the end, the sendMail function gets called on the transporter object. This will simply send the mail and do the errorhandling. If an error occures, we will log it to the console.


Please make sure to set your own gmailaccount in the mailoptions and in the sendEmail function.

Add bootstrap to the project

Download and extract bootstrap to following folderstructure:
DownloadUrl: getboostrap.com

<yourprojectroot>
|__public
    |__css
    |__js
    |__fonts


create a file layout.jade with following code
This will add the baselayout with a little navigation   

Add a homepage to your project

Create a file named "index.jade" and add it to your view folder


Start your webserver

go to your projectroot and run
$ node app.js

Use your contactform

Now you can surf http://localhost:3000/contact and fill out the form.
After submitting your form you will get a "message send" to your console and you will recieve your email in your gmail account


If your mail gets rejected......

To test your email sending,  you have to allow "less secure apps" in your gmail testaccount:

You can do this by following :

https://support.google.com/accounts/answer/6010255?hl=enhttps://support.google.com/accounts/answer/6010255?hl=en







Samstag, 20. August 2016

node.js: create your first express webserver

In the last tutorial, we have created a simple webserver. That was great as preperation to use the expressframework, which can handle the webserverstuff for us. Let's have a look to express.

Prerequisits

node.js installed
npm installed

Install express globaly

$ npm install -g express

Create a npm project

Create your project rootfolder "express-project" and open a terminal in that folder and typpe:
$ npm init

Follow the intstructions on your terminal.

Add needed dependencies

Open package.json and add your dependencies. My package.json looks like that:

You can just pick the "dependencies" object 

 

Add you dependencies

Create a file "app.js" and paste following code
This will reference your dependencies and setup your express webserver.
As you can see, the webserver will be bound on port 3000 and it will return a simple "Hello world" response and will log the same words to the console.

Start the webserver

Open a terminal in the projectroot and type:
$ node app.js 


Now you can surf http://localhost:3000 and you should see "Hello world"

Thats it