How to Generate Certificate in React JS
Creating a certificate generation feature in a React application can be a valuable addition, especially for educational platforms, events, and workshops. This blog post will guide you through the steps to generate certificates using React JS.
Prerequisites
Before we start, make sure you have the following:
- Basic understanding of React JS.
- Node.js and npm installed on your machine.
- A React application set up. You can create one using
create-react-app
if you don't have an existing project.
Set Up Your React Project
If you don’t have a React project set up, create one using the following command:
npx create-react-app certificate-generator cd certificate-generator
You will need a few libraries to handle image manipulation. Install this using npm:
npm install html-to-image
Create a new file Certicate.js
:
import React from 'react' import './certificate.css' import certificateTemplate from './certificate.png' import { useState, useCallback, useRef } from 'react' import { toPng } from 'html-to-image'; const Certicate = () => { const ref = useRef(null) const [name,setName] = useState('') const [course,setCourse] = useState('') const onButtonClick = useCallback(() => { if (ref.current === null) { return } toPng(ref.current, { cacheBust: true, }) .then((dataUrl) => { const link = document.createElement('a') link.download = 'certificate.png' link.href = dataUrl link.click() }) .catch((err) => { console.log(err) }) }, [ref]) return ( <div> <input type='text' placeholder='Enter Name' value={name} onChange={(e)=>setName(e.target.value)}/> <input type='text' placeholder='Enter course' value={course} onChange={(e)=>setCourse(e.target.value)}/> <div className='container' ref={ref}> <img src={certificateTemplate} height={400}/> <div className='content'> <h1>{name}</h1> <p>{course}</p> </div> </div> <button onClick={onButtonClick}>Click me</button> </div> ) } export default Certicate
Create the CSS file certificate.css
for styling:
.container{ height: 400px; width: 560px; /* background: red; */ position: relative; } .content{ position: absolute; height: 100%; width: 100%; top: 0; left: 0; /* background-color: rebeccapurple; */ } .content h1{ margin-top: 150px; margin-left: 190px; } .content p{ margin-top: -6px; margin-left: 300px; } button{ margin-top: 10px; height: 40px; width:100px; border: none; background-color: orange; color: #fff; border-radius: 5px; }
Testing
Run your React application using:
npm start
Navigate to http://localhost:3000
in your browser. You should see the certificate template and a "Download Certificate" button. Clicking the button will generate and download the certificate.
Conclusion
You now have a simple React application that generates certificates and allows users to download them. You can further customize the certificate design, add input fields for dynamic data, and enhance the functionality based on your requirements.
Watch Video