In this tutorial, we will learn how you can get updated value from child component to parent component in React.
Let’s say you have a parent child component in your React app. You are sending data from parent to child and your child component is updating that variable’s value. Now when you get the value in parent component, you still get the original value, not the updated one.
First, you need to create a reference and pass it to the child component.
function Parent() {
// Create a reference
const childRef = React.useRef();
// Create array of users
const [users, setUsers] = React.useState([
{ id: 1, name: "Adnan" },
{ id: 2, name: "Afzal" }
]);
// Function to get updated users
function getUsers() {
// Get users with reference
let tempUsers = [];
if (childRef.current) {
tempUsers = childRef.current.getUsers();
}
console.log({
"users": users,
"tempUsers": tempUsers
});
}
// Set child component and pass users array to it
return (
<>
<Child users={ users }
ref={ childRef } />
{/* Button to get users */}
<button type="button" onClick={ function () {
getUsers();
} }>Get users</button>
</>
);
}
childRef: First, we are creating a reference.
users: Then we are creating a state variable.
getUsers(): A function is created that will get the state value using reference.
We are passing the users array and reference to the child component.
A button is also created which when clicked, will call the function to get the state variable.
Then in your child component, you need to create it using forwardRef.
// Create child component that gets properties
// Export child using forward reference
const Child = React.forwardRef(function (props, ref) {
// Get users from parent component
const [users, setUsers] = React.useState(props.users || []);
// Use imperative handler to return updated value
React.useImperativeHandle(ref, function () {
return {
getUsers() {
return users;
}
};
});
// Function to set user name to "Khalid" where user ID is 1
function updateUser(id, name) {
const tempUsers = JSON.parse(JSON.stringify(users));
for (let a = 0; a < tempUsers.length; a++) {
if (tempUsers[a].id == id) {
tempUsers[a].name = name;
break;
}
}
setUsers(tempUsers);
}
// Create button to update user
return (
<>
<button type="button" onClick={ function () {
updateUser(1, "Khalid");
} }>Update user</button>
</>
);
});
forwardRef: It is used to pass ref from parent component to child component.
Then creating a state variable and initialize it with props value received from parent component.
We are using imperative handler to return the updated value.
A button is created in child component that updates the value using it’s ID.
JSON.parse(JSON.stringify(users)): We are first converting the users array to JSON, then converting back to Javascript array. This ensures a deep copy.
That’s how you can get updated value from child component to parent component in React.
A multi-purpose platform is created in Node.js and MongoDB. Developing an API in Node.js and MongoDB allows you to create real-time, high performance and scalable applications. When you are building a website or a mobile app, you might have a different design than what is already built. But your backend will be almost similar to your competitor. Let’s say you want to build a social network like Facebook. You will pick an HTML template or design a UI specific for your business. But you want to have a module to create users, posts, pages, groups, friends, chats and much more.
So we are providing you a multi-purpose platform that allows you to use social network, job portal, manage your media files and much more. It is a self-hosted script so all the data will be stored on your server, no third-party storage service is used here.
Tech stack ๐ป
Bootstrap 5+
React 18+
Node.js 20+
MongoDB 4+
User Registration and Profile ๐๐ปโโ๏ธ
This API allows you to register an account. The passwords are encrypted before saving them in database. User can also login using his email and password that he entered during registration.
On successfull login, a Json Web Token (JWT) is generated and returned in the API response. The client application needs to save that token in its local storage because that token will be use in other APIs in headers to identify the user. This token is also stored in server as well. So if you want to logout a user manually, you can simply remove his token from database.
User can edit his name and profile image. The email field is read-only, it cannot be changed. User can also change his password. For that, he needs to provide his current password and enter his new password 2 times for confirmation.
Social Network Posts ๐
If you are building a social network, then this module allows you to create and manage posts for a social network. You can also share other’s posts on your timeline. You can edit or remove your own posts. Other users will be able to like, comment or share your posts. Users will be able to edit to delete their own comments. You will be able to reply to the comments on your posts, and you can also edit or remove your reply if you want. Users can also see the list of all users who has liked or shared your post.
Pages ๐
If you are running a business, you can create a page for your business and start posting about your products or services in that page. In order to create a page, you need to set it’s name, tell a little about the page, and provide a cover photo for the page. User can follow your page and start seeing your page’s posts in their newsfeed. Only creator of page can create a post in that page.
You can see a list of all users who has followed your page. User can also see a list of all pages he has followed. The owner of the page can edit or delete the page. Once page is deleted, all the posts inside that will be deleted as well.
Groups ๐ฅณ
You can create groups to create a community of like-minded people. In order to create a group, you need to enter the name of group, a little description about the group and it’s cover photo. You can see a list of all groups created in the platform. There are separate links from where you can see only the groups that you have created or the groups you have joined. You can join or leave the group whenever you want. However, admin of the group can also remove you from the group if he wants.
Only admin or group members can post in a group. Posts uploaded by admin will be immediately displayed on the groups newsfeed. However, the posts uploaded by group members will be held pending for approval from the admin. Admin can see a list of all posts uploaded by group members. He can accept or decline a post he wants.
Admin of the group can update the name or description of the group, and he can also change the cover photo of the group. Admin can delete the group as well. Upon deleting, all the posts uploaded in that group will be deleted as well.
Media ๐
This API allows you to upload media files (images, videos) on the platform. Each media file will have a title, alt attribute, and caption. These will help you in your Search Engine Optimization (SEO). You can edit or delete your own media files whenever you want.
Friends ๐๐ป
You can create friends by sending them a friend request, just like you do in Facebook. Other user can see a list of all friend requests he has received. He can accept or decline your request. If accepted, then you both will become friends and you can chat with each other. You can see a list of all of your friends. At any point, you can remove a user from your friend list.
Realtime Chat ๐ฌ
You can have realtime chat with your friends. Chats are end-to-end encrypted, that means that the messages are encrypted before sending to the server. And they are decrypted only after receiving the response from the server. Your messages will remain secure in-transit.
For realtime communication, we are using Socket IO. When you send a message, an event is emitted. The receiver will be listening to that event and display a notification alert that you have received a new message. If the chat is already opened, then the new message will automatically be appended at the bottom of the chat.
Since this is a multi-purpose platform and it is developed in scalable technologies (Node.js & MongoDB), a job portal platform is also added that allows recruiter to post jobs and candidates can apply on that job. Recruiter can see all the applications he has received on a job and can change the status of applicant to shortlisted, interviewing, rejected or selected etc. Candidate can upload multiple CVs and choose the relevant CV while applying for the job. Recruiter can update or delete the job any time.
You can also filter job applications by status. So if you are recruiter, you will post a job. Then you will start receiving applications from candidates. Recruiter can change the status from interviewing to shortlisted employess. Then recruiter can change the status to interviewing. Recruiter can also reject the candidate, but he also needs to provide a reason for rejection. Finally, recruiter can set the candidate as “Hired”. So there must be a way for recruiter to filter job applications by their status.
We also have a PHP and MySQL version of Job Portal website. You can get it from here.
Admin Panel ๐จ๐ปโ๐ผ
An admin panel is created where you can manage all the users, social network posts and jobs created on the platform. It is a single page application created in React JS and can be deployed as a sub-domain to your main website.
Super admin can see the list of all users. He can add a new user if he wants. An email with password set by admin will be sent to the new user. Admin can also update the user password as well. He can also delete the user, all the posts uploaded by that user will be deleted as well.
Super admin can see all the posts uploaded on social network platform. Just like users, he can delete any post he did not feel appropriate.
Admin can also see all the jobs posted by recruiter and if any job post goes against the standards, super admin can remove it.
Blogs ๐
Since this is a multi-purpose platform, so I added a blog module that allows you to write articles on your website. Admin can create blogs from admin panel and they will be displayed on user side. User can post a comment if they are logged-in. Other users or admin can reply to their comments. Admin can manage all posts and comments from admin panel. Admin can delete any post or command he did not find suitable.
We are using sockets to update the blogs in realtime. So if user is reading a post and admin changes something from admin panel, it will immediately gets updated on user side. User does not need to refresh the page.
Page Builder ๐
We are using page builder to create blog posts. It allows you to create paragraphs, headings, images, videos and buttons.
You can set the attributes like id and class. You can also set CSS properties of each tag.
If you are using image or video, you can add alt and caption attributes as well.
Freelance Platform ๐จ๐ปโ๐ป ๐ค
This multi-purpose platform project also has a freelance platform where you can hire experts to get your job done. Or, if you are a skilled person, you can find work there.
There are 2 entities in freelance platform: Buyer ๐ฐ and Seller ๐ค. Buyer will create a task to be done, he will mention his budget and deadline. Buyer must have sufficient balance in their account. They can add balance using Stripe. ๐ณ
Sellers will start bidding on that task. Seller will also send a proposal mentioning how he will get the work done, what is his offer and in how many days he will do it. ๐
Buyer will see all the bids from sellers. He will also see a freelance profile of each bidder, telling the orders done by each seller, their ratings and reviews etc. โญ๏ธ
Buyer can accept the bid of any seller he seems fit for the job. The seller will be notified and their order will be started. โฐ
On their order detail page, they can chat with each other. They can send messages ๐ฌ with attachments ๐งท. At any point, buyer or seller can cancel the order.
After the work is done, buyer can complete the order โ . Once it is completed, the amount that was offered in the bid will be deducted from buyer’s account. 5 percent will be deducted as a “platform fee”, and the remaining 95% of the amount will be added in the seller’s account ๐ค.
Buyer can also gives ratings โญ๏ธ to a seller and also can give a review about his experience. This will help seller build his freelance profile.
Seller can withdraw the money by entering his bank account details ๐ฆ. These details will be sent to the admin panel ๐จ๐ปโ๐ผ. Admin can transfer the funds and once the transfer is completed, seller’s balance will be returned to 0.
Notifications ๐
User will receive a notification when:
His freelance order gets completed/cancelled.
A new message has been received on his order.
His bid got accepted on freelance project.
His withdrawl request has been updated.
Someone commented on his post.
Someone replied to his comment.
Someone likes his post on social network.
His post has been shared by someone.
These notifications will be displayed as a bell icon ๐ on header when user is logged-in. If he has any unread notifications, then it will be displayed as read.
Unread notification’s background will be gray. On clicking the notification, it will be marked as read.
Installer ๐คน๐ปโโ๏ธ
Run the following commands in your “admin” folder:
npm install
npm start
In order to create a super admin, you need to run the following command in your “premium-api” folder once:
node installer.js
This will create a super admin in your database. You can set the email and password of your choice from “installer.js” file.
Paste the “multi-purpose-platform-nodejs-mongodb” folder in your “htdocs” folder if you are using XAMPP or MAMP, or in “www” folder if you are using WAMP.
Run the following commands in the “premium-api” folder:
More features can also be added on-demand in this multi-purpose platform. If you do not want all the features, we can remove or change features as per your needs.
Hello. In this post, we will show you, how you can split a camel case word and capitalize it using regex (regular expression) in Javascript.
Input
Output
adnanTechCom
Adnan Tech Com
Following code will split the camel case into multiple words and then capitalize it:
// splitting camel case to multiple words
const str = "adnanTechCom".replace(/([a-z])([A-Z])/g, "$1 $2")
// capitalizing the string
const capitalize = str.charAt(0).toUpperCase() + str.slice(1)
console.log(capitalize)
capitalize variable will now have value:
Adnan Tech Com
This regular expression will search for all words that ends with small letter and begin with capital alphabet. Then give a space between each of such word.
The above replace call replaces the match of the regex (which happens to match everything) with the first capture group ($1) followed by a space, followed by the second capture group ($2).
For capitalization, you can also use a CSS property as well:
In this article, we are going to discuss 10 useful Javascript libraries that you need to use in almost every web project. We will discuss the following libraries along with their use:
Sweetalert
Datetime Picker by XD Soft
Socket IO
DataTable
RichText
PDFObject
Vue JS
Notify JS
Chart JS
TimeCircles
1. Sweetalert
Sweetalert is a JS library used to display alert messages. You can also use it for displaying confirm messages i.e. ask for the user’s confirmation before performing any action. To display a simple alert message:
swal({
title: "Confirm",
text: "Are you sure, this data will be removed ?",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((isOkay) => {
if (isOkay) {
//
}
});
Learn more about how to use the confirmation dialog properly from here. You can also use it as a prompt:
swal("Enter your name:", {
content: "input",
})
.then((value) => {
if (value == "") {
return false;
}
console.log(value);
});
You can read more about it from their official page.
2. Datetime Picker by XD Soft
It is a JS library that is used to display a calendar with a date and time picker. You can use it to get the user’s date of birth during registration. The basic usage is, you need to give your input field a unique ID:
<input type="text" id="datetimepicker" />
Then you can display the datetimepicker by calling the function:
jQuery("#datetimepicker").datetimepicker();
Make sure you have jQuery included in your project, this library requires jQuery. You can see this library in action from here. The complete documentation of this library is found on their official page.
3. Socket IO
Socket IO is used for real-time communication. If you are working on a feature that requires data from the server after regular intervals, there are 2 options to achieve this:
Polling
Sockets
Polling
This technique requires calling an AJAX request to the server every few seconds. This will overload the server with a lot of requests. There will be a lot of unnecessary requests to the server and if you have a lot of users, then your website might get crashed.
Sockets
The solution to the above problem is the sockets. Sockets attach a listener to the client-side and emit events from the server. The client is continuously listening to that event, whenever that event is received, the client will perform the action accordingly.
The difference between Polling and Sockets can be explained by this example:
For example, you are going on a trip with your family. Your Dad is driving the car and you are in the back seat. And you are continuously asking your Dad “did we reached the destination ?” every few minutes. This is Polling.
And in the other case, you ask your Dad “please inform me when we reach our destination”. Now you are silently listening to your Dad, who will send an event to you only when you reached your destination. This is Socket.
This library is used to display data in tabular form. It has a built-in search feature, that allows you to search the entire table. You can search value from any row from any column. The search is case insensitive so you do not have to worry about capital or small letters.
It also has a sorting feature that allows you to sort the data based on any column. It also allows you to decide how many records you want to show on one page (e.g. 25, 50, 75, or 100). It has built-in pagination based on the number of records you are displaying on one page.
Its usage is rather simple. You just need to give your table tag a unique ID:
<table id="table"></table>
Then in your Javascript, simply initialize the library:
$("#table").DataTable();
It also requires jQuery to be included in your project. You can see this library in action from here. You can learn more about it from their official page.
5. RichText
This library applies to your textarea tag. It makes your text area as WYSIWYG (What You See Is What You Get). It enhances the Textarea field and gives it more options like:
Text formatiing (font size, bold, italic, underline, color).
Text alignment (left, center, right, justify).
Headings & paragraphs.
Upload images.
Attach URLs.
Adding tables.
Or you can even add HTML tags too.
Its usage is almost the same as the DataTable library. You need to give your textarea a unique ID:
<textarea id="content" name="content"></textarea>
And in your Javascript, you need to initialize it like this:
$("#content").richText();
This library also requires jQuery to be included. Full documentation of this library can be found here.
6. PDFObject
When working with PDF files, if you want to show PDF files from your website, you have 3 options:
Make the PDF file downloadable, so user can view it offline too.
Display the PDF in a new window or tab.
Embed the PDF in your website specific section.
This library fulfills the 3rd approach. It embeds the PDF file in your website using a div tag. Place a div tag anywhere in your code where you want to show the PDF file:
<div id="pdf"></div>
Then in your Javascript, initialize the library with a URL of the PDf file:
Vue JS is more a framework than a library. But since it can be integrated with any project whether it is in core PHP, Laravel, WordPress, or Node JS, it can be called a library. You can learn all functions of it from their official guide. You can check our following projects developed in Vue JS:
You will learn a lot about Vue JS from the above projects.
8. Notify JS
This lightweight library is used to display notification pop-ups on the corners of the browser window. This library also requires jQuery to be included before using it. Its usage is extremely easy, you simply need to call the following function when you want to show the notification:
$.notify("New message");
By default, it displays a pop-up on the top right, but you can decide the position of it. You can learn more about this library from here.
9. Chart JS
As the name suggests, this library is used to draw charts and graphs on your website. You can show statistics to the users using this library. It uses canvas to render charts. The following code will create a simple bar chart:
There are many graphs & charts provided by this library. You can learn the implementation of all chars from their official page.
10. TimeCircles
This is used to create a countdown timer. You can set the date and the timer will start counting down till that time. This also requires jQuery on your website. Its usage is simple, you just need to give a data-date attribute to the div tag where you want to show the countdown timer. data-date attribute’s value will be the date and time when the timer hits zero. Give it a unique ID so it can be accessible in Javascript.
You should learn all the libraries above and create small programs in them. But then you need to create a web application where you should apply all the above libraries together. We are going to give you a simple task that helps you learn how to combine all libraries together to create great web applications.
Assignment
Create a simple website that inputs date using DateTimePicker, description using RichText, an input field to upload PDF files and a submit button. When the submit button is pressed, it should show a message using Sweetalert that the message has been sent. It should send an event to the server using Socket IO and the other user should receive that event and display the description in a table using DataTable.
Another user should also see a notification using NotifyJS that a new event has been received. You need to show a countdown timer using TimeCircles till the date field value ends. You should also display the uploaded PDF file in a div tag using the PDFObject library.
Complete assignment’s frontend should be done in Vue JS. If you face any problem in doing this assignment, kindly do let us know in the comments section below.