Code News

Creating a Blogging App Using React, Part 5: Profile Page

  • In the previous part of this tutorial series, you saw how to implement the update and delete post feature for our React blog application. In this tutorial, you'll implement the profile page for the blog application.

    Getting Started

    Let's get started by cloning the source code from the last part of the series.

    Once the directory has been cloned, navigate to the project directory and install the required dependencies.

    cd ReactBlogApp-EditDelete npm install

    Start the Node.js server and you will have the application running at http://localhost:7777/index.html#/.

    Creating the Profile Page View

    First you need to add a new menu item in the home page menu called Profile. On the home.html page, add a new ul element for the Profile page as shown:

    <ul class="nav nav-pills pull-right"> <li role="presentation" id="homeHyperlink" class="active"><a href="#">Home</a></li> <li role="presentation" id="addHyperLink"><a href="/home#/addPost">Add</a></li> <li role="presentation" id="btnProfile"><a href="/home#/showProfile">Profile</a></li> <li role="presentation"><a href="#">Logout</a></li> </ul>

    Save the above changes and restart the server. Point your browser to http://localhost:7777/ and sign in to the application. Once logged in, you will be able to view the menu list with the profile link.

    For the profile menu link to work, you need to add a new route to the existing routes in the home.jsx file.

    ReactDOM.render( <Router history={hashHistory}> <Route component={ShowPost} path="/"></Route> <Route component={AddPost} path="/addPost(/:id)"></Route> <Route component={ShowProfile} path="/showProfile"></Route> </Router>, document.getElementById('app'));

    In the home.jsx file, create a new component ShowProfile. Add some state variables for name, password, email, and Id. Inside the render method of the ShowProfile component, add the HTML for rendering the profile details. Here is how the ShowProfile component looks:

    class ShowProfile extends React.Component { constructor(props) { super(props); this.state = { name:'', email:'', password:'', id:'' }; } componentDidMount(){ document.getElementById('addHyperLink').className = ""; document.getElementById('homeHyperlink').className = ""; document.getElementById('profileHyperlink').className = "active"; this.getProfile(); } updateProfile(){ } getProfile(){ } render() { return ( <div className="col-md-5"> <div className="form-area"> <form role="form"> <br styles="clear:both" /> <div className="form-group"> <input value={} type="text" onChange={this.handleNameChange} className="form-control" placeholder="Name" required /> </div> <div className="form-group"> <input value={this.state.password} type="password" onChange={this.handlePasswordChange} className="form-control" placeholder="Password" required /> </div> <button type="button" onClick={this.updateProfile} id="submit" name="submit" className="btn btn-primary pull-right">Update</button> </form> </div> </div> ) } }

    When the profile page is loaded, you need to fetch the details from the database and populate it in the form. Add the code in the getProfile method inside the ShowProfile component to make the AJAX call to get details about the user.'/getProfile', { }) .then(function (response) { }) .catch(function (error) { console.log('error is ',error); });

    Once the details are received in the response, you need to update the state variables for the same. Here is the getProfile method from the ShowProfile component:

    getProfile(){ var self = this;'/getProfile', { }) .then(function (response) { if(response){ self.setState({}); self.setState({}); self.setState({}); } }) .catch(function (error) { console.log('error is ',error); }); }

    Inside the app.js file, create a method called getProfile which will handle the POST method call from the ShowProfile's getProfile method. The getProfile method inside the app.js file will instead make a call to user.js to get details from the database. Here is how it looks:'/getProfile', function(req,res){ user.getUserInfo(sessions.username, function(result){ res.send(result) }) })

    Inside the user.js file, create a method called getUserInfo which will query the MongoDB database using the username to get the required details. Here is how the getUserInfo method looks:

    getUserInfo: function(username, callback){ MongoClient.connect(url, function(err, db){ db.collection('user').findOne( { email : username },function(err, result){ if(result==null){ callback(false) } else{ callback(result); } }); }); }

    As seen in the above code, you make a call to the MongoDB using the MongoClient to query the user collection based on the email address. Once the result is received, it's returned back to the callback function. 

    Save the above changes and restart the Node.js server. Point your browser to http://localhost:7777/#/ and log in to the application. Click the profile link in the menu and you will be able to view the profile details populated on the page.

    Updating the User Profile

    To handle the name and password change, you need to define two methods called handleNameChange and handlePasswordChange in the ShowProfile component. These methods will set the state variables on text change. Here is how it looks:

    handleNameChange(e){ this.setState({}) } handlePasswordChange(e){ this.setState({}) }

    Bind the methods in the ShowProfile constructor.

    constructor(props) { super(props); this.handleNameChange = this.handleNameChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.updateProfile = this.updateProfile.bind(this); this.getProfile = this.getProfile.bind(this); this.state = { name:'', email:'', password:'', id:'' }; }

    Define a method called updateProfile which will be called when the user clicks on the Update button to update the user details. Inside the updateProfile method, make a POST call to the updateProfile method in the app.js file along with the changed name and password. Here is how the updateProfile method in the ShowProfile component looks:

    updateProfile(){ var self = this;'/updateProfile', { name:, password: this.state.password }) .then(function (response) { if(response){ hashHistory.push('/') } }) .catch(function (error) { console.log('error is ',error); }); }

    Once a response is received from the POST call, the screen is navigated to the blog post list.

    Inside the app.js file, create a method called updateProfile which will parse the passed-in parameters and make a call to the MongoDB database.'/updateProfile', function(req, res){ var name =; var password = req.body.password; user.updateProfile(name, password, sessions.username, function(result){ res.send(result); }) })

    As seen in the above code, once the parameters are parsed in the updateProfile method in the app.js file, the user.updateProfile method is called with changed name, password, and username. 

    Let's define the user.updateProfile method inside the user.js file, which will make a call to the MongoDB database and update the name and password based on the username. Here is how the updateProfile method in the user.js file looks:

    updateProfile: function(name, password, username, callback){ MongoClient.connect(url, function(err, db) { db.collection('user').updateOne( { "email": username }, { $set: { "name" : name, "password" : password } },function(err, result){ if(err == null){ callback(true) } else{ callback(false) } }); }); }

    In the above code, you updated the user details based on the email address using the updateOne method.

    Save the above changes and restart the server. Log in to the application and click on the Profile link. Change the name and password and click the Update button. Try to sign in, and you will be able to log in using the new password. 

    Wrapping It Up

    In this tutorial, you implemented the profile page for the blog application. You learnt how to fetch details from a database and populate it on the page using React. You also implemented the functionality to update profile details.

    Source code from this tutorial is available on GitHub. Do let me know your thoughts or any suggestions in the comments below.

    3 days 16 hours ago

Doxing Is a Perilous Form of Justice—Even When It's Outing Nazis

Trick Out Your Dorm With Cool Gear Even Students Can Afford

NASA's Rocket to Nowhere Finally Has a Destination

When Government Rules by Software, Citizens Are Left in the Dark