Web Dev for Beginners

After a few weeks of on and off work I was able to finalize my personal website, which I encourage you to visit (http://joshsurette.com/index.html). Through this process, I was able to expand my previously limited knowledge on modern web dev tools, and given the fact that this was a bit of a grueling process, I wanted to post here to share some code examples and info to help you get going on your own starter projects.

1. React.js:

React is a great UI tool developed by Facebook for dynamic UIs. The framework provides an Object Oriented approach, and relies on a DOM (document object model) to give functionality to various UI components to allow for things like component-specific re-rendering. But enough theoretical talk…below Ill post two examples to highlight some major components to understand:

 

handleNewRowSubmit: function(e) {
e.preventDefault();
var newRow = { “id”: this.state.data.length, “firstName”: this.firstname.value, “lastName”: this.lastname.value, “url”: this.url.value, “description”: this.description.value };

// Writes data to Firebase instance
firebase.database().ref().push(newRow);

// Create copy of immutable state array, push element, and set the state to this new appended copy
var arrayVar = this.state.data.slice();
arrayVar.push(JSON.parse(‘{}’));
arrayVar[arrayVar.length – 1].id = arrayVar.length;
arrayVar[arrayVar.length – 1].firstName = this.firstname.value;
arrayVar[arrayVar.length – 1].lastName = this.lastname.value;
arrayVar[arrayVar.length – 1].url = this.url.value;
arrayVar[arrayVar.length – 1].description = this.description.value;
this.setState({data: arrayVar});

// Clear the form for next entry
this.firstname.value=””;
this.lastname.value=””;
this.url.value=””;
this.description.value=””;
return;
},

render: function() {
var headerComponents = this.generateHeaders(),
rowComponents = this.generateRows();

return (

{rowComponents}

this.firstname = FirstName} placeholder=”First Name”/>
this.lastname = LastName} placeholder=”Last Name”/>
this.url = URL} placeholder=”Source URL”/>
this.description = Desc} placeholder=”Source Summary”/>

</form>
<form onSubmit={this.loadData}>

</form>
</div>
);

}

React.render(<Table cols={cols} initialData={initialData}/>, document.getElementById(‘table’));

Lets start with the React.render right above here. Here I instantiate my table class, which is where the functions above reside in. The ‘cols’ and ‘initialData’ are props, which allow you to pass data between various classes. You can access these in the Table class using this.props.cols syntax, which in this case allows me to access data from Firebase (more on this later).

Along with this, also notice the this.state.data, which is a critical piece to know as a React beginner. Unlike props, states are inherent to that specific class, and should be treated as PRIVATE. This is great for instances where the component has dynamic data it needs to monitor.

Another thing you’ll notice is we return what seems to be HTML tags, which is what actually builds our UI. However, what this actually is is JSX notation, which means we need separate tools (trust me…youll here this a lot in web dev) to actually turn this into HTML. For this, look into Babel, which is a loader to process this JSX. Also, look into Webpack, which allows you to specify Babel builds (ie: what files, where the output will go, etc.)

2. Bootstrap

Bootstrap is a styling package that gives you a bunch of preset CSS styles, which saves a ton of time. Bootstrap relies on a grid system, which you can see in the code below:

<div class = “container-fluid” style=”margin-top:100px;margin-bottom:20px;”>
<div class = “col-md-4 col-md-offset-1”>

The major takeaway here is noticing the ‘col-md-*’ notation. This is referring to the UI grid, and how Bootstrap separates the screen into 12 columns to allow you to more effectively style your UI. Simply go on their site and download their bootstrap.css files to place them in your project.

3. Firebase:

Although I was able to get experience with MongoDB and MySQL databases running locally on my computer, Firebase is Google’s cloud database service and is INCREDIBLY easy to use, and was essential to my website. Firebase is a NoSQL, JSON database and is able to process asynchronous requests as each JSON object sent to the database is assigned a timestamp key. Simple go to the Firebase console website and create a database. Initializing the database to have your site/app connect is also really simple, and you can find this in the Firebase console:

var config = {
apiKey: “”,
authDomain: “”,
databaseURL: “”,
projectId: “”,
storageBucket: “”,
messagingSenderId: “”
};
firebase.initializeApp(config);

var database = firebase.database();

var initialData = [];
database.ref().once(‘value’, function(snapshot) {
snapshot.forEach(childSnap =>{
initialData.push(childSnap.val());
})
});

This code serves to get a snapshot, or instance, of my database and stores each value in an array for later use. This is precisely how my CrowdSource (http://joshsurette.com/crowdSource.html) page works to display data. It is worth noting that once does NOT continuously listen for database changes. If you want a continuous, realtime update of data rather than just one snapshot on the page load, you would use ‘on’ instead of ‘once’.

var newRow = { “id”: this.state.data.length, “firstName”: this.firstname.value, “lastName”: this.lastname.value, “url”: this.url.value, “description”: this.description.value };

// Writes data to Firebase instance
firebase.database().ref().push(newRow);

This code above shows how to write to the database…it really is this easy. This code is from my function which handles my form data. I create a JSON object out of the form data, and then, using my database reference, just push to the database. This push makes sure I don’t overwrite existing data, but you can use other functions like ‘update’ to update specific fields. Firebase really is a great tool that I highly recommend, and is one I find easier to use than MySQL or MongoDB.

4. Node.js/Express

Although in my site, most of my backend is Firebase, I also experimented a lot with Node, which allows you to create a server to handle HTTP requests and respond accordingly. Node is great to use with MongoDB, and I could replace my Firebase with Node/MongoDB. NOTE that to write these servers, you use Express, which allows you to write Middleware and has higher level functions to make writing code easier. Middleware basically refers to things like bodyparsing, or any other operations prior to backend work like database storage, or GET requests from other servers. Check out the code below, which demonstrates some of the basics of instantiating Express, and some basic HTTP requests:

// Handles form submits from FAQ.html
app.post(‘/submitForm’, function(req, res){
var data = req.body;
fs.appendFile(‘./test.txt’, data.fn + ‘ ‘ + data.inputEmail + ‘ ‘ + data.subject + ‘ ‘ + data.message + ‘\n’, function(error) {
if (error) throw error;
});
});

app.get(‘/submitForm’, function(req,res){
res.sendfile(‘FAQ.html’);
});

This is an example I was experimenting with to write data from a form to a file. Here, we see we have a function with req (request) and res (response), and you can see here in the GET I set the response to return a webpage. In the POST, I obtain the the body of the form and extract data based on the ids of the form fields. We can also see below how Node works with MySQL databases:

var mysql = require(‘mysql’);
var router = express.Router();

var connection = mysql.createConnection({
host: ‘localhost’,
user: ‘surettej_admin’,
password: ‘NashuaSouth3’,
database: ‘surettej_contactSubmits’
});

connection.query(‘CREATE DATABASE IF NOT EXISTS contactSubmits’, function (err) {
if (err) throw err;
connection.query(‘USE contactSubmits’, function (err) {
if (err) throw err;
connection.query(‘CREATE TABLE IF NOT EXISTS people(‘
+ ‘name VARCHAR(30),’
+ ’email VARCHAR(30),’
+ ‘subject VARCHAR(30),’
+ ‘message VARCHAR(500)’
+ ‘)’, function (err) {
if (err) throw err;
});
});
});

Here we can see a connection setup, and then a simple SQL query using this connection. This is just a snapshot of the stuff you can do with Node and Express, and given that I did not use it much in this project, Id like to employ in an app in the future.

I hope this article helped you get started on your own web dev projects, and I encourage you to leave comments below either about my website, or some other cool tools you’ve worked with.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s