Creating Register page with ReactJS | LinkTree Project
This tutorial is a part of the Series ‘Complete FullStack LinkTree Project with MERN‘. This Project covers beginner to Intermediate level implementation of MongoDB, Express, ReactJS, NodeJS, and NextJS.
Project Walkthrough
Users can signup on the LinkTree website and start creating their LinkTree right away. They get a user profile editing page, edit or customize links page, a Dashboard to edit and track the links, and many more.
I’ve created a YouTube series on this Project in 6 parts. This Code snippet is from the 2nd part where we have created a Register page.
Frontend
import React, { useState } from "react";
import styles from "../styles/apply.module.css";
import Footer from "../components/Footer";
import { toast } from "react-toastify";
import Link from "next/link";
import { useRouter } from "next/router";
const Apply = () => {
const router = useRouter();
const [handle, setHandle] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [category, setCategory] = useState("");
const [submitted, setSubmitted] = useState(false);
const handleCategoryChange = (e) => {
setCategory(e.target.value);
};
const handleRegister = (e) => {
e.preventDefault();
if (!category) return toast.error("Add a category");
// backend part
fetch("http://localhost:8080/api/register", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify({
handle,
email,
password,
category
})
})
.then((res) => res.json())
.then((data) => {
console.log(data);
if (data.status === "success") {
toast("You are registered successfully");
localStorage.setItem("LinkTreeToken", data.token);
setSubmitted(true);
router.push("/login");
}
})
.catch((err) => {
toast.error("Try a different username");
});
};
return (
<>
<section
className={
styles.background + " min-h-screen flex justify-center items-center"
}
>
<div className="main">
<div className="content bg-white border-2 px-4 py-8 rounded-2xl shadow-lg">
<h1 className="text-2xl font-bold text-center">
Join the top 1% creators
</h1>
<p className="text-center">Create Linktree for your brand</p>
<p className="text-center py-5 font-bold text-gray-500">
Start building your Hub
</p>
<form
onSubmit={handleRegister}
className="flex flex-col gap-4 text-lg mt-5"
>
<span className="flex flex-row shadow-md border-2 px-3 py-2 rounded-md focus:outline-none">
<img className="w-6 mr-2" src="/svg/ig.svg" alt="" />
<input
value={handle}
onChange={(e) => setHandle(e.target.value)}
className="focus:outline-none"
type="text"
placeholder="Social Handle"
required
/>
</span>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
className="shadow-md border-2 px-3 py-2 rounded-md focus:outline-none"
type="email"
placeholder="Enter your email"
required
/>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
className="shadow-md border-2 px-3 py-2 rounded-md focus:outline-none"
type="password"
placeholder="Set a password"
required
/>
<h5 className="text-sm text-center text-indigo-400">
Account Type:
</h5>
<span className="flex">
<label className="flex flex-row mr-3">
<input
type="checkbox"
className=""
value="Creator"
checked={category === "Creator"}
onChange={handleCategoryChange}
/>
<p className="pl-2">Creator</p>
</label>
<label className="flex flex-row mr-3">
<input
type="checkbox"
className=""
value="Agency"
checked={category === "Agency"}
onChange={handleCategoryChange}
/>
<p className="pl-2">Agency</p>
</label>
<label className="flex flex-row mr-3">
<input
type="checkbox"
className=""
value="Brand"
checked={category === "Brand"}
onChange={handleCategoryChange}
/>
<p className="pl-2">Brand</p>
</label>
</span>
<input
className="bg-indigo-600 text-white py-2 rounded-lg cursor-pointer"
type="submit"
value="Apply"
/>
</form>
</div>
<h4 className="text-center text-white pt-3">
Already have an account?{" "}
<Link className="font-bold text-red-400" href="/login">
Login
</Link>
</h4>
</div>
</section>
<Footer />
</>
);
};
export default Apply;
Backend
const express = require("express");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
mongoose.set("strictQuery", false);
const { registerUser } = require("./controllers/auth");
require("dotenv").config();
app.use(cors());
app.use(express.json());
mongoose
.connect("mongodb://127.0.0.1:27017/linkTree-9")
.then(() => {
console.log(`mongodb COnnected`);
})
.catch((err) => {
console.log(err.message);
});
app.get("/", (req, res) => {
res.send(`Server is running on port ${port}`);
});
app.post("/api/register", registerUser);
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
onst User = require('../models/user');
const jwt = require('jsonwebtoken');
const registerUser = async(req, res)=>{
const { handle, email, password, category } = req.body;
console.log(req.body);
try {
const defaultLink = { url: 'typefinance.com', title: 'TypeFinance', icon: 'https://typefinance.com/favicon.ico'}
const user = await User.create({handle, email, password, role: category, links: [defaultLink]});
const token = jwt.sign({email: email}, process.env.SECRET_JWT);
console.log('user', user);
return res.json({message: 'user created', status: 'success', 'token': token, id: user._id});
} catch (err) {
if(err.code === '11000'){
return res.json({message: "Try different handle or email", status: 'error'});
}
return res.json({message: err.message, status: 'error'});
}
}
module.exports = {registerUser};
Summing up
Here are the resources used in the tutorial, NextJS Featured Template: On GitHub (opens in a new tab) NextJS Documentation: Docs (opens in a new tab) Tailwind CSS: Tailwind (opens in a new tab)
I hope this part of the tutorial on the Fullstack LinkTree Project was helpful to you. If you faced any problems while following the video or the source code snippets, comment below and I’ll reply as soon as possible. See you soon.