Getting started on building a personal website/webapp with React

Preda W.
9 min readAug 1, 2017

--

TL;DR fork and clone the public starter repo kit on GitHub and npm install in the terminal to get started from here: https://github.com/pa87901/repoStarterKit
If you like my start kit repository, please give it a star.

Building your own website with JavaScript is fulfilling and exciting. The slowest part for me was commencing the project and the focus of this post is to enable readers to understand one approach to getting started. From then, a developer can extend it with different styles and functionality in any way they choose.

The steps I took to getting started were:
1. File architecture
2. Setting up the basic environment in Node
3. Installing the React framework
4. Creating a webpack and configuration
5. Building the basic front-end components
6. Styling and CSS
7. Viewing on local host
8. Deploying on Heroku

File architecture

If you choose to fork my repo, you can ignore steps 3 and 4 in the “Setting up the basic environment” section, as well as the “Creating a webpack and configuration” section.
Start by creating a .gitignore file in the root folder of your repo.

touch .gitignore

The .gitignore file ensures that certain files are ignored when committing and pushing upstream to GitHub or your deployment platform. In this .gitignore file, paste the following:

# Logs
logs
*.Logs
# Compiled directory and file
build/
bundle.js
# Dependency directories
node_modules/

If you choose to initiate your own repo, you can still view mine for guidance on structuring your own client folders.
The client folders to create are:
react-client/dist
react-client/src

mkdir react-client
cd react-client
mkdir dist
mkdir src

The files you will need to create are:
package.json (which should be created in the root folder)
react-client/dist/index.html
react-client/src/index.js
These can be created by navigating to the relevant folder in your terminal and entering:

touch <filename>

index.js serves as the entry point of our application where we point to all our .js files.
index.html serves as the root of the application. Initialise your index.html with the following html code:

<!DOCTYPE html>
<html>
<head>
<title>My website</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

Setting up the basic environment

Node will be the environment that we use for creating your web application. If you do not already have Node installed on your computer, this will be the first step. If you have already installed Node, skip to step 3 below.

1. Download Node from nodejs.org.
2. In the terminal, run the following command:

sudo npm install -g

3. Start new web application via the terminal with the command:

npm init

4. Follow the steps to create a package.json file which lists all the dependencies for your web application to run. You can always install new dependencies and add to this file later on.
5. If you do not have nodemon installed, look into installing nodemon globally. It is a tool that watches your files for any changes that are saved and restart your node application. Run the following command in the terminal:

sudo npm install -g nodemon

Import the expressjs library with the following terminal command:

npm install express --save
npm install body-parser --save

Initiate your server folder and root server file.

mkdir server
cd server
touch index.js

Get your server/index.js started with this code:

const express = require('express');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 8080;
const path = require('path');
const app = express();
app.use(bodyParser.json());
app.use(express.static(`${__dirname}/../react-client/dist`));
app.get('*', (req, res) => {
res.sendFile(path.resolve(`${__dirname}/../react-client/dist/index.html`));
});
app.listen(PORT, () => {
console.log(`listening on port ${PORT}!`);
});

Installing the React framework

The front-end framework for this tutorial is React. You can install the React framework through the terminal with the following commands:

npm install react --save
npm install react-dom --save

React Router is a very useful navigational tool for React applications. As at May 2022, we’ll use version 5:

npm install react-router-dom@^5 --save

Creating a webpack

As a developer, it is best practice to keep our code modular and separate for better organisation and ease of navigation. It is also more readable and easier for other developers to follow our code. In contrast however, the web browser prefers fewer files in order to read our code and render it to the view. Webpack is a tool that combines our separate code files into one called a “bundle” file which the browser can then interpret.

Install webpack as a dependency by running the following command in the terminal. As of May 2022, the version of webpack available is 5.

npm install webpack --save
npm install webpack-cli --save-dev

Add the following webpack and node scripts to your package.json file:

"scripts": {
"dev": "webpack --mode development --watch",
"start": "node ./server/index.js",
"build": "webpack --mode production",
"react-dev": "webpack --mode development --watch",
"server-dev": "nodemon server/index.js"
},

In your index.html folder, add the following script just before </body>:

<script type="text/javascript" src="bundle.js"></script>

This script is where the index.html file will output the bundle.js file that is created by webpack.

Install babel dependencies (a brief explanation about Babel will follow shortly):

npm install babel-core --save
npm install babel-loader --save
npm install babel-preset-react --save

Configuring webpack
1. Create a file called webpack.config.js in the root of your repository.

touch webpack.config.js

2. Copy the following code below and paste into this file:

const path = require('path');
const SRC_DIR = path.join(__dirname, '/react-client/src');
const DIST_DIR = path.join(__dirname, '/react-client/dist');
const webpack = require('webpack');
module.exports = {
entry: `${SRC_DIR}/index.js`,
output: {
path: DIST_DIR,
filename: 'bundle.js',
},
module : {
rules : [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.png$/,
type: 'asset/resource'
},
{
test: /\.jpg/,
loader: 'file-loader',
},
{
test : /\.jsx?/,
include : SRC_DIR,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react']
}
}
],
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV' : JSON.stringify('production')
}),
],
};

This configuration defines what the entry and output points are for our application.

Webpack also needs to be configured to load certain file types that we will use in building our website, e.g. a CSS file, image files such as .png and .jpg files, and babel-loader with presets. The babel-loader is important as React makes heavy use of ES6, which will be used to build components for our application. Babel compiles code written in ES6 to ES5 so that all browsers can interpret the JavaScript code correctly.

Building the basic components

I assume here that you already know how to build in React. If not, it is worthwhile reading up on React through online resources and tutorials.

The entry point for our React components is react-client/src/index.js, which we already created. In this file, enter the following:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(
<App />,
document.getElementById('app')
);

<App /> is the first component to be rendered to the virtual DOM as evident within the ReactDOM.render method.

Create a new folder called Components within react-client/src/. Within the Components folder, create a new file called App.js. This component will also store the routes for the various (React) routes that you will use to navigate your website. This is where we use React-Router for your website. Within App.js, initiate the code as follows:

import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import NavBar from './headerComponent/NavBar';
import Footer from './footerComponent/Footer';
const App = () => (
<BrowserRouter>
<div>
<NavBar />
<Route name="home" exact path="/" component={HomePage} />
<Route name="about" exact path="/about" component={AboutPage} />
<Footer />
</div>
</BrowserRouter>
);
export default App;

HomePage
The home page can be created in the same directory as the App.jsx component with the name HomePage.jsx and starter code:

import React, { useState } from 'react';const HomePage = () => {
const [count, setCount] = useState(0);
return (
<div className="main">
<h1 className="centered">Home page</h1>
<div>
This is a simple div to show how React states can work in React Hooks. Feel free to remove this div when building your personal home page.
<div>
Count: {count}
<div>
<button onClick={() => setCount(count + 1)}>
Increment count
</button>
</div>
</div>
</div>
</div>
);
}
export default HomePage;

NavBar
A navigation bar is great to store easy links to pages of your website.
Within your Components folder create a subfolder called HeaderComponent and here create a new React component called NavBar.jsx with the following starter code:

import React from 'react';
import { Link } from 'react-router-dom';
const NavBar = () => (
<header>
<ul id="headerButtons">
<li className="navButton"><Link to="/">Home</Link></li>
<li className="navButton"><Link to="/about">About</Link></li>
</ul>
</header>
);
export default NavBar;

Footer
If you want to include a footer to your website to include links to your external resources such as social media sites, create a FooterComponent subfolder and create a new React component called Footer.jsx with the following starter code:

import React from 'react';const Footer = () => (
<footer>
<div>
<p>Footer component</p>
<p>This is where some additional notes about your website go.</p>
</div>
</footer>
);
export default Footer;

These three basic components are enough to get you started on building the structure of your personal website. Ensure that you include the new NavBar and the Footer components in your App component, adjacent to the first route to the HomePage component that we included previously.

Styling and CSS

Create a CSS style sheet in the same folder (react-client/dist) as index.html and name it styles.css.

Include a script tag to your index.html file above </head> to point to your style sheet.

<link rel="stylesheet" href="styles.css">

If you want to use bootstrap, you can include a script tag for this too in the same section.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

To get started with styling the NavBar and Footer components, include these styles below. You can always change them depending on how you want to style your website.

header {
display: block;
background-color: black;
width: 100vw;
height: 10vh;
color: white;
}
#headerButtons {
list-style-type: none;
display: flex;
flex-direction: row;
justify-content: flex-end;
}
.navButton {
margin: 3vh;
}
.main {
height: 75vh;
padding: 1% 3%;
}
footer {
display: block;
width: 100%;
height: 15vh;
background-color: black;
color: white;
}
.centered {
display: flex;
justify-content: center;
align-items: center;
}

I highly recommend a UI library called Semantic UI React to style your website and make it look professional. I have written another blog post that introduces the elements that tend to be highly used. Please read if you are interested.

Viewing on localhost

As you build your website, further you will want to view your site.
In the terminal, run the following commands in separate windows respectively:

npm run react-dev
npm run server-dev

Open your website on localhost in a web browser by typing the following in the address bar and you should see the initial stages of your website before you build further.

http://localhost:8080/

Deploying to Heroku

The last step is to deploy your site on a cloud platform such as Heroku. A very useful point of information is on the “Deploying React with Zero Configuration” post which can be found at: https://blog.heroku.com/deploying-react-with-zero-configuration

Add a couple more (postinstall/postbuild) scripts to your package.json:

"postinstall": "webpack",
"heroku-postbuild": "webpack --mode production"

These scripts essentially instruct Heroku how to build the application after installing. In this case, we use webpack to build our application.

Since we have our git repo for our website already, all we need to do is create a new app in Heroku under the personal apps section and give it an appropriate name such as “personalwebsite”.

Then in the root directory of our git repo, we enter the following terminal command. You can swap out the name “personalwebsite” for another name that you used for your repo instead.

heroku git:remote -a personalwebsite

Now after adding and committing changes to your repo, and pushing to your origin in GitHub, push to Heroku as well with this terminal command:

git push heroku master

Heroku will then install and attempt to build your application upstream. After successful installation, and postbuild, you should hopefully see the following log extract.

remote:        Running heroku-postbuild
remote:
remote: > trial@1.0.0 heroku-postbuild /tmp/build_3d75db5bfd5f9501f4e0127fbd8b4135
remote: > webpack -p
remote:
remote: Hash: ee7102c9062f6903f0d4
remote: Version: webpack 3.4.1
remote: Time: 6143ms
remote: Asset Size Chunks Chunk Names
remote: bundle.js 195 kB 0 [emitted] main
remote: [91] ./react-client/src/index.js 480 bytes {0} [built]
remote: + 213 hidden modules
remote:
remote: -----> Caching build
remote: Clearing previous node cache
remote: Saving 2 cacheDirectories (default):
remote: - node_modules
remote: - bower_components (nothing to cache)
remote:
remote: -----> Build succeeded!
remote: -----> Discovering process types
remote: Procfile declares types -> (none)
remote: Default types for buildpack -> web
remote:
remote: -----> Compressing...
remote: Done: 19.6M
remote: -----> Launching...
remote: Released v3
remote: https://repostarterkit.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/repostarterkit.git
* [new branch] master -> master

This means that Heroku was able to successfully build and deploy your application. Instructing Heroku to open your application or navigating to the url created for your Heroku app should render your website.

If you found this post useful in any way, please give this article a few claps and give my start kit repo a star!

Happy building!

--

--