In the previous part of this tutorial series, you saw how to implement the profile page feature for the React blog application. In this tutorial, you’ll see how to implement tags for the blog posts.
Getting Started
Let’s get started by cloning the source code from the last part of the series.
https://github.com/royagasthyan/ReactBlog-Profile
Once the directory has been cloned, navigate to the project directory and install the required dependencies.
cd ReactBlogApp-Profile npm install
Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.
Creating the Tag Page
Let’s start by creating a link for the user to add a tag to the MongoDB database. In the index.html
page, add one more li
for the Add Tag
page.
When the user clicks the Add Tag
link, it should display the AddTag
React component. So let’s add a route for the Add Tag
component in the home.jsx
file.
Here is the complete route list:
ReactDOM.render(, document.getElementById('app'));
Let’s create the AddTag
component which will be rendered when the user clicks the Add Tag link.
class AddTag extends React.Component { constructor(props) { super(props); } componentDidMount(){ document.getElementById('addHyperLink').className = ""; document.getElementById('homeHyperlink').className = ""; document.getElementById('profileHyperlink').className = ""; document.getElementById('tagHyperlink').className = "active"; } render() { return () } }
As seen in the above code, inside the AddTag
react component class you have rendered the basic HTML template for the page. Inside the componentDidMount
method you have class name to make the AddTag
hyperlink active.
Save the above changes and restart the server. Sign into the application and click on the Add Tag link, and you will be able to view the Add Tag
page.
Implementing the Add Tag Functionality
Define a state variable to keep track of the tag change.
constructor(props) { super(props); this.state = { tag:'' }; }
Attach the tag state variable to the input element in the render method.
As seen in the above code, you have also attached an onChange
event to the input to keep track of its value change. Bind the onChange
method handleTagChange
inside the constructor.
constructor(props) { super(props); this.handleTagChange = this.handleTagChange.bind(this); this.state = { tag:'' }; }
Now let’s define the handleTagChange
method inside the AddTag
React component.
handleTagChange(e){ this.setState({tag:e.target.value}) }
When the user clicks the Add button to add the tag, you need to save the data. So let’s attach an onClick
event to the input button.
Bind the addTag
method inside the React component constructor and define the method to make an API call to the Node.js server endpoint.
constructor(props) { super(props); this.addTag = this.addTag.bind(this); this.handleTagChange = this.handleTagChange.bind(this); this.state = { tag:'' }; }
Next let’s define the addTag
method to make the API call to the /addtag
end point.
addTag(){ axios.post('/addtag', { tag: this.state.tag }) .then(function (response) { console.log('reponse from add tag is ',response); }) .catch(function (error) { console.log(error); }); }
Let’s create the Node.js API endpoint for /addTag
. Inside the app.js
file, create the /addTag
route, which will parse the data and insert the data into the MongoDB database.
app.post('/addtag', function (req, res) { var tag = req.body.tag; post.addTag(tag,function(result){ res.send(result); }); })
Inside the /addTag
endpoint, you have a made a call to a method called addTag
from the post.js
file. Let’s create the addTag
method inside the post.js
file. Here is how it looks:
addTag: function(tagName, callback){ MongoClient.connect(url, function(err, db) { db.collection('tag').insertOne( { "name": tagName },function(err, result){ assert.equal(err, null); console.log("Saved the tag details."); if(err == null){ callback(true) } else{ callback(false) } }); }); }
As seen in the above code, you have used MongoClient
to connect to the MongoDB database. You have inserted the tag data into a collection called tag inside the database. Once the data has been inserted without any error, Boolean true is passed to the callback function. If an error is encountered, a Boolean false is returned to the callback function.
Save the above changes and restart the server. Sign in to the app and click on the Add Tag link. Enter a tag name and click the Add button. Check the browser console and you should be able to see the success message logged in the browser console.
Populating the Tags on the Add Post Page
Once you have added the tags from the Add Tag
page, tags need to be populated in the Add post
page. Let’s start by creating a method called getTags
inside the post.js
file which would connect to the MongoDB database and fetch the tags. Here is how it looks:
getTag: function(callback){ MongoClient.connect(url, function(err, db){ db.collection('tag', function (err, collection) { collection.find().toArray(function (err, list) { callback(list); }); }); }) }
As seen in the above code, you have used the MongoClient to connect to the MongoDB database. Once the collection has been fetched, it’s been converted to array using the toArray
method and then passed to the callback function.
Next create the Node.js API endpoint which will call the above getTag
method in app.js
.
app.post('/gettag', function (req, res) { post.getTag(function(result){ res.send(result); }); })
In the home.jsx
file inside the AddPost
component, create a method called getTags
which will make the /gettag
API call and fetch the tag list.
getTags(){ var self = this; axios.post('/getTag', { }) .then(function (response) { if(response){ self.setState({tags:response.data}); } }) .catch(function (error) { console.log('error is ',error); }); }
Once the data has been fetched from the API, set the data inside the tags
state variable.
Inside the render method of the ShowPost
React component, add the select HTML element to bind the tags
state variable. Here is how it would look:
As seen in the above code, you have used the map
method to map the tags
state variable to the select element.
Inside the componentDidMount
method, make a call to the getTags
method to load tags once the component has mounted.
componentDidMount(){ document.getElementById('addHyperLink').className = "active"; document.getElementById('homeHyperlink').className = ""; document.getElementById('profileHyperlink').className = ""; document.getElementById('tagHyperlink').className = ""; this.getPostWithId(); this.getTags(); }
Save the above changes and restart the server. Once you have loaded the Add Post
page, you should have the tags loaded in a select HTML element.
Let’s add a default option in the drop-down with value 0.
You have added an onChange
event to the select HTML element. Here is what the handleTagChange
event looks like:
handleTagChange(e){ this.setState({tag:e.target.value}) }
Once the user selects the tag, the value will be available in the state variable tag
.
Include the tag
variable in the addPost
method in the AddPost
React component.
addPost(){ axios.post('/addPost', { title: this.state.title, subject: this.state.subject, tag: this.state.tag, id: this.props.params.id }) .then(function (response) { console.log('response from add post is ',response); hashHistory.push('/') }) .catch(function (error) { console.log(error); }); }
Change the /addpost
API endpoint to include the tag
parameter.
app.post('/addpost', function (req, res) { var title = req.body.title; var subject = req.body.subject; var tag = req.body.tag; var id = req.body.id; console.log('id is ',id); if(id == '' || id == undefined){ console.log('add'); post.addPost(title, subject ,tag,function(result){ res.send(result); }); } else{ console.log('update',title,subject); post.updatePost(id, title, subject ,tag,function(result){ res.send(result); }); } })
Modify the addPost
method in the post.js
file to include the tag
parameter.
addPost: function(title, subject,tag, callback){ MongoClient.connect(url, function(err, db) { db.collection('post').insertOne( { "title": title, "subject": subject, "tag": tag },function(err, result){ assert.equal(err, null); console.log("Saved the blog post details."); if(err == null){ callback(true) } else{ callback(false) } }); }); }
Modify the getPostWithId
method to set the drop-down when the post detail is fetched.
getPostWithId(){ var id = this.props.params.id; var self = this; axios.post('/getPostWithId', { id: id }) .then(function (response) { if(response){ self.setState({title:response.data.title}); self.setState({subject:response.data.subject}); self.setState({tag:response.data.tag}) } }) .catch(function (error) { console.log('error is ',error); }); }
Save the above changes and restart the server. Sign in and navigate to the Add Post page and add a post with a tag selected. You will have the new post saved and listed. Click on the edit button to edit the post details and tag.
Wrapping It Up
In this tutorial you saw how to implement the add tag page. You added the tag field to the add post page along with title and subject fields.
Hope you enjoyed this tutorial series. Do let us know your thoughts, suggestions or any corrections in the comments below.
Source code from this tutorial is available on GitHub.
Powered by WPeMatico