In the previous part of this tutorial series, you saw how to implement the sign-up and sign-in functionality. In this part of the tutorial, you’ll implement the user home page and the functionality to add and display the blog posts.
Getting Started
Let’s get started by cloning the source code from the first part of the tutorial.
https://github.com/royagasthyan/ReactBlogApp-SignUp
Once the directory has been cloned, navigate to the project directory and install the required dependencies.
cd ReactBlogApp-SignUp npm install
Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.
Creating the User Home Page
Once the user tries to sign in to the application, you need to validate the user credentials and, if valid, create a session. To use sessions in a Node.js app, you need to install express-session
using Node Package Manager (npm).
npm install express-session --save
Require the express-session
in the app.js
file.
var session = require('express-session');
To use the session, you need to set a session secret.
app.use(session({secret: 'my-secret'}));
Now define a variable called sessions
in the global scope.
var sessions
Assign the sessions
variable in the /signin
method using the request parameter.
sessions=req.session;
Using the sessions
variable, you keep the signed-in username in session.
sessions.username = user_name;
Create a file called home.html
inside the html
folder in the application. Here is how it looks:
React Blog App React Blog App
List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
Create an express route called /home
which will render the home page for a valid user.
app.get('/home', function (req, res) { if(sessions && sessions.username){ res.sendFile(__dirname + '/html/home.html'); } else{ res.send('unauthorized'); } })
As seen in the above code, when the user is redirected to the /home
route, if sessions
and sessions.username
exist, the home page is rendered.
Modify the signin
method to send a success response on successful user validation.
app.post('/signin', function (req, res) { sessions=req.session; var user_name=req.body.email; var password=req.body.password; user.validateSignIn(user_name,password,function(result){ if(result){ sessions.username = user_name; res.send('success'); } }); })
The above success response is parsed on the React side and, if successful, the user is redirected to the /home
express route. In the main.jsx
file, inside the Signin
component inside the signIn
method, modify the code to redirect to the home page.
signIn(){ axios.post('/signin', { email: this.state.email, password: this.state.password }) .then(function (response) { if(response.data == 'success'){ window.location.assign('http://localhost:7777/home') } }) .catch(function (error) { console.log(error); }); }
Save the above changes and restart the Node server. Sign in using a valid username and password, and you will be redirected to the home page.
Modify the above blog post display into a React component. Create a file called home.jsx
. Inside the home.jsx
file, create a React component called ShowPost
which will render the blog post list. Move the static HTML inside the React component render method. Here is how the ShowPost
React component looks:
class ShowPost extends React.Component { constructor(props) { super(props); } render() { return () } }List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
List group item heading
Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.
Modify the home.html
page to include the required React libraries. Here is the modified home.html
page:
React Blog App React Blog App
As seen in the above HTML code, the container div has been named app
, inside which the React components will be displayed.
Save the above changes and restart the node server. Sign in to the blog application and, once on the home page, you will have the ShowPost
React component rendered.
Now you need to dynamically populate the values in the post list. Before doing that, let’s create a page to add a post. On clicking the above Add
hyperlink, you need to display the page to add the blog post.
Add Post React Component
Let’s create an add post React component to add the blog posts. It will consist of a title input box and a subject text area. In the home.jsx
, create an AddPost
React component to add blog posts. Here is how the AddPost
React component looks:
class AddPost extends React.Component { render() { return () } }
When the user enters the title and the post subject, you need to handle the text change events in the React component. Add the following change event handler to the AddPost
React component.
handleTitleChange(e){ this.setState({title:e.target.value}) } handleSubjectChange(e){ this.setState({body:e.target.value}) }
Add the on change event to the AddPost
render HTML.
Bind the state variables and the events in the React constructor method.
constructor(props) { super(props); this.handleTitleChange = this.handleTitleChange.bind(this); this.handleSubjecChange = this.handleSubjectChange.bind(this); this.state = { title:'', subject:'' }; }
When the user clicks on the Add Post
button, you need to post the title and subject from the React user interface to the Node.js back end to save it in the MongoDB database. Create a method called addPost
in the AddPost
React component to post the title and subject to the Node.js request handler. Here is how the addPost
method in the AddPost
React component looks:
addPost(){ axios.post('/addPost', { title: this.state.title, subject: this.state.subject }) .then(function (response) { console.log('response from add post is ',response); hashHistory.push('/') }) .catch(function (error) { console.log(error); }); }
As seen in the above code, you have used axios
to post the blog post details to the Node.js server.
Now you need to create a post module which will deal with adding and getting the post details. Create a file called post.js
in the project directory. In the post.js
file, export an addPost
method which will insert post details into the MongoDB database. Require the MongoClient
and create the addPost
method to insert post details in the MongoDB database. Here is how the post.js
file looks:
var MongoClient = require('mongodb').MongoClient; var assert = require('assert'); var url = 'mongodb://localhost:27017/Blog'; module.exports = { addPost: function(title, subject, callback){ MongoClient.connect(url, function(err, db) { db.collection('post').insertOne( { "title": title, "subject": subject },function(err, result){ assert.equal(err, null); console.log("Saved the blog post details."); if(err == null){ callback(true) } else{ callback(false) } }); }); } }
As seen in the above code, you connected to the MongoDB database using the connector and inserted a record. Once the operation is executed, you checked the error, if any, and returned the status to the callback function.
Inside the app.js
file, create a request handler called addPost
which will call the addPost
method from post.js
. Here is how it looks:
app.post('/addpost', function (req, res) { var title = req.body.title; var subject = req.body.subject; post.addPost(title, subject ,function(result){ res.send(result); }); })
Save the above changes and restart the Node.js server. Log in to the application, click on the Add link, and enter the details to add a post. Once done, click on the Add Post button and the details should be saved in the MongoDB database.
Display Post React Component
First you need to fetch the saved post details from MongoDB. Inside the post.js
file, create a method called GetPost
which will fetch post details. Here is how it looks:
getPost: function(callback){ MongoClient.connect(url, function(err, db){ db.collection('post', function (err, collection) { collection.find().toArray(function (err, list) { callback(list); }); }); }) }
The above code fetches details from the MongoDB collection, converts it into a list, and sends it back to the callback function. In the home.jsx
file, inside the ShowPost
component, fetch the post details in the componentDidMount
method. Here is how it looks:
componentDidMount(){ var self = this; axios.post('/getPost', { }) .then(function (response) { }) .catch(function (error) { console.log('error is ',error); }); }
The above code makes a post request to the Node.js server method /getPost
which will call the getPost
method in the post.js
file. Here is the /getPost
method in the app.js
file.
app.post('/getpost', function (req, res) { post.getPost(function(result){ res.send(result); }); })
Once the post details have been fetched in the axios
success callback, keep the details inside a state array variable. Declare a variable called posts
inside the ShowPost
constructor.
constructor(props) { super(props); this.state = { posts:[] }; }
In the success callback of the axios
ajax call, set the state variable as shown:
self.setState({posts:response.data})
Once you have the post details, you need to dynamically create the required HTML in the React component’s render method. Here is how it looks:
render() { return ({ this.state.posts.map(function(post,index) { return) }{post.title}
{post.subject}
}) }
The above code iterates the posts
state variable and creates the HTML dynamically. Save the above changes and restart the Node.js server. Sign in to the blog application and create a few blog posts using the Add button on the home page. Once the posts have been added, they will get displayed on the home page.
Wrapping It Up
In this tutorial, you saw how to create React components for adding and displaying blog posts. In the next part of this tutorial series, you’ll learn how to add the functionality to delete and update the blog posts.
Let me know your thoughts about this tutorial in the comment section below. Source code from this tutorial is available on GitHub.