Skip to main content

One post tagged with "inspirational quotes"

View All Tags

Inspirational Quotes with React 3D Effect

· 4 min read
Phill Dellow
Jargonator Extrodenarie
Go to DentralisedNZ
Issuing and Verification of EntraId VerifiedID Credentials on Azure B2C

In this post, I'm excited to showcase a modern React component that combines some of the coolest features of React and CSS to create a 3D parallax card. Each time you hover, the card dynamically changes colors and fetches a new quote from an external API when clicked.

This component demonstrates:

  • 3D Parallax Effect: The card tilts based on mouse movement.
  • Dynamic Backgrounds: A new gradient background on each hover.
  • Real-Time Quote Fetching: Random quotes to keep you inspired.

Check it out below!

"Loading inspiration..."

-

Click to refresh inspiration ✨

How It Works

This component uses advanced React techniques like useState and useEffect to interact with the DOM, fetching data from an API and applying dynamic CSS styles to give a smooth user experience.

Click the card for a new dose of inspiration!

So lets just jump straight into the React components code to see how we've put this one together.

First we import a couple of things

import React, { useState, useEffect } from 'react';
import './MindBlowingCard.css';

Yes we will have a look at that .css in a minute but back at the component we are

const MindBlowingCard: React.FC = () => {
const [quote, setQuote] = useState<string>('Loading inspiration...');
const [author, setAuthor] = useState<string>('');
const [gradient, setGradient] = useState<string>('');

// Fetch a new quote on initial render
useEffect(() => {
fetchQuote();
}, []);

const fetchQuote = async () => {
try {
const response = await fetch('https://api.api-ninjas.com/v1/quotes?category=happiness', {
headers: {
'X-Api-Key': 'thisismyrealfreeapikey.fromtheapi-nijas' // Replace with your actual API key
}
});
const data = await response.json();
const quoteData = data[0]; // Access the first item in the array
setQuote(quoteData.quote);
setAuthor(quoteData.author);
} catch {
setQuote('Believe in the of you!');
setAuthor('Unknown');
}
};

Youcan see in the first few lines we set up some variables then the code goes away to call this 'fetchQuote' method.

'fetchQuote' is an async calling off to our family friendly and free quote provider at the api-ninjas, recieving back a JSON with the quote and authors details and gracefully handling any errors coming back by displaying a default cryptic quote.

Next we'll set up some colour for our cards styling

  const generateGradient = () => {
const colors = ['#FF6B6B', '#FFD93D', '#6BCB77', '#4D96FF', '#D14DFF'];
const color1 = colors[Math.floor(Math.random() * colors.length)];
const color2 = colors[Math.floor(Math.random() * colors.length)];
setGradient(`linear-gradient(135deg, ${color1}, ${color2})`);
};

So this is a bit of a dynamically generated variable that create contains a colour gradient from one colour to another. It takes five HEX colours (yeah it sounds like black magic I reckon) and, it randomly selects from two of these five colours. The two selected colors to create a CSS linear-gradient at a 135-degree angle.

By passing this gradient to the setGradient function, it updates the component’s background style dynamically.

Now with 3D

Lets bring those two things together in out last bit of code and add to the top of it some cool 3D effects

  return (
<div
className="mind-blowing-card"
onMouseMove={(e) => {
const card = e.currentTarget;
const { width, height, left, top } = card.getBoundingClientRect();
const x = ((e.clientX - left) / width - 0.5) * 60; // Calculate tilt based on mouse position
const y = ((e.clientY - top) / height - 0.5) * -60;
card.style.transform = `rotateY(${x}deg) rotateX(${y}deg)`;
}}
onMouseLeave={(e) => {
const card = e.currentTarget;
card.style.transform = 'rotateY(0) rotateX(0)';
generateGradient();
}}
style={{ background: gradient }}
onClick={fetchQuote}
>
<h2 className="quote">"{quote}"</h2>
<p className="author">- {author}</p>
<p className="click-text">Click to refresh inspiration ✨</p>
</div>
);

This starts off with a trigger of a MouseMove, then getBoundiingClientReact() is going to calculate the cards position and dimensions.

Based on the mouse position within the card, the x and y variables set the rotation degrees. This calculation tilts the card more as the cursor moves toward the edges.

Then card.style.transform applies a rotateY (horizontal tilt) and rotateX (vertical tilt) effect to create the 3D effect.