Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Build a document generator with Express using REST API
Next article icon

Build a Jokes Generator With Next JS and API

Last Updated : 01 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Jokes generator application using Next Js is an application where we are using the external API to fetch the jokes. This application has features to copy the jokes and when the user clicks on "Get a Joke" new jokes will be generated.

Preview of final output: Let us have a look at how the final output will look like.

Build-a-Jokes-Generator-With-Nextjs-and-API

Prerequisites:

  • Introduction to Next.js
  • React Hooks
  • NPM or NPX

Approach to create Joke Generator:

  • In this Next.js application, the­ initial step involves defining a state­ through the utilization of useState. This allows for the­ management of three­ crucial elements: joke­, error, and copySuccess.
  • The proce­ss of retrieving a random joke from an e­xternal API is handled by the ge­tJoke function. It effective­ly resets any existing e­rrors and clears the copy success me­ssage. In case there­ is a failure in making an API request, it will e­stablish an error message accordingly.
  • On the­ other hand, the handleCopyClick function utilize­s the clipboard API to enable copying of the­ joke text. Upon successful comple­tion, it exhibits a "Copied!" message­ to confirm this action.
  • To enhance user e­xperience and promote­ usability, this application offers a clean and responsive­ user interface incorporating both a "Ge­t a Joke" button as well as a "Copy" button. For enhance­d SEO optimization purposes, appropriate page title­ and description have bee­n duly set.

Steps to create the Next JS App:

Step 1: Create a new Next.js project using the following command

npx create-next-app  jokes-generator-app

Step 2: Change to the project directory:

cd  jokes-generator-app

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"@fortawesome/fontawesome-svg-core": "^6.4.2",
"@fortawesome/free-solid-svg-icons": "^6.4.2",
"@fortawesome/react-fontawesome": "^0.2.0",
"html2canvas": "^1.4.1",
"next": "^13.0.6",
"qrcode.react": "^3.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.11.0"
}

Example: In this example, we will create the Jokes Generator App Using NextJs. Write the following code in App.js and App.css file

CSS
.container {     text-align: center;     background: rgba(255, 255, 255, 0.9);     width: 500px;     height: 350px;     font-family: 'Arial', sans-serif;     margin: 30px auto;     padding: 60px;     max-width: 800px;     background-color: white;     box-shadow: 0 2px 26px 0px rgba(0, 0, 0, 0.1);     border-radius: 15px;     border: 3px solid #ccc; }  .title {     font-size: 28px;     font-weight: bold;     color: #0984e3;     margin-bottom: 24px; }  .jokeText {     font-size: 24px;     font-weight: 400;     color: #333;     line-height: 1.4; }  .button, .copyButton {     background: #0984e3;     color: white;     border: none;     border-radius: 10px;     padding: 15px;     font-size: 16px;     font-weight: bold;     cursor: pointer;     transition: background-color 0.3s;     margin: 10px; }  .button:hover, .copyButton:hover {     background: #1453a5; }  .errorText {     color: #ff6b6b;     font-weight: bold;     margin-top: 16px;     font-size: 18px; } 
JavaScript
import { useState } from 'react'; import Head from 'next/head'; import './App.css';  export default function Home() { 	const [joke, setJoke] = useState(''); 	const [error, setError] = useState(null); 	const [copySuccess, setCopySuccess] = useState(false);  	const getJoke = () => { 		// Reset any previous errors 		setError(null); 		// Reset the copy success message 		setCopySuccess(false);  		fetch('https://icanhazdadjoke.com/', { 			headers: { 				Accept: 'application/json', 			}, 		}) 			.then((response) => { 				if (!response.ok) { 					throw new Error('Failed to fetch joke'); 				} 				return response.json(); 			}) 			.then((data) => { 				setJoke(data.joke); 			}) 			.catch((error) => { 				setError('Failed to fetch joke. Please try again later.'); 				console.error(error); 			}); 	};  	const handleCopyClick = () => { 		navigator.clipboard.writeText(joke).then(() => { 			// Set copy success message 			setCopySuccess(true); 		}); 	};  	return ( 		<div className="container"> 			<Head> 				<title>Random Jokes Generator</title> 				<meta name="description" 					content="Random Jokes Generator" /> 			</Head>  			<div className="app"> 				<div className="card"> 					<h1 className="heading"> 						Random Jokes Generator 					</h1> 					<div className="jokeContainer"> 						{error ? ( 							<p className="errorText">{error}</p>):( 							<> 								<p className="jokeText">{joke}</p> 								<button className="copyButton" 									onClick={handleCopyClick}> 									{copySuccess ? 'Copied!' : 'Copy'} 								</button> 							</> 						)} 					</div> 					<button className='button' onClick={getJoke}> 						Get a Joke 					</button> 				</div> 			</div> 		</div> 	); } 

Step 3: Run this command to start the application:

npm run dev

Step 4: To run the next.js application use the following command and then go to this URL:

 http://localhost:3000

Output:


Next Article
Build a document generator with Express using REST API
author
saurabhkumarsharma05
Improve
Article Tags :
  • ReactJS
  • Web Technologies
  • Next.js

Similar Reads

  • How to Build a REST API with Next.js 13?
    Next.js is the most widely used React framework. Next.js 13.2 introduced a new file-based routing mechanism, called App Router, for building React frontend and serverless backend. In this article, we will be building a simple REST API using Next.js Route Handlers Table of Content Next.js Route Handl
    7 min read
  • Build a document generator with Express using REST API
    In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume
    2 min read
  • Build a Notes App with Next.js
    Note-taking App is a simple web application that allows users to create, edit, and delete text notes. The app provides a user-friendly interface for managing notes, making it easy to add new notes, update existing notes, and delete notes when they are no longer needed. The app provides a way for use
    4 min read
  • Joke generator App Using Angular
    Angular has become one of the most popular frameworks for building dynamic web applications. In this project, we build a simple yet entertaining Joke generator app using Angular. The app will fetch random jokes from a public API and display them to the user. This project will help us understand how
    4 min read
  • Build a Dictionary App Using Next Js
    In this article, we'll create a dictionary app using Next Js. The application allows use­rs to effortlessly search for word de­finitions, parts of speech, and e­xample. By utilizing an online dictionary API, the app fetche­s relevant word data and organizes it in a structure­d manner. Users can also
    4 min read
  • Create a Quiz App with Next JS and Tailwind
    We’ll explore the process of building a Quiz App utilizing NextJS and Tailwind. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz. Prerequis
    6 min read
  • QR Code Generator Service with Node.js and Express.js
    Nowadays, Quick Response (QR) codes have become an integral tool for transferring information quickly and conveniently. This project aims to develop a QR code generation API service using Node.js and Express.js. In addition, it goes further and extends the former by providing more customization opti
    5 min read
  • Create a Quiz App with Next JS
    In this article, we’ll explore the process of building a Quiz App utilizing NextJS. The quiz app provides users with a series of multiple-choice questions with options. Users can select the option and move to the next question. At the end, the user will be able to see the analysis of the quiz. Outpu
    5 min read
  • Music Player App with Next.js and API
    In this tutorial, we'll create a Music Player App using NextJS, a React framework. Explore frontend development, API integration, and UI design to build a user-friendly app for seamless music enjoyment. Join us in harmonizing code and creativity to craft an engaging Music Player App with NextJS in t
    3 min read
  • Create a Quote Generator Web App with Pure JavaScript using an API
    In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API. Application Requirements: Bootstrap 4 CDNAPI : https://type.fit/api/quotesJavaScriptHTMLSteps: Follow the below steps to create a quote generator. Step 1 Fetch: We are using inbuilt fet
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences