import { useRef, useState, useEffect } from "react";
export const InputSpotlightBorder = () => {
const boxRef = useRef(null);
useEffect(() => {
const boxElement = boxRef.current;
if (!boxElement) {
return;
}
const updateAnimation = () => {
const angle =
(parseFloat(boxElement.style.getPropertyValue("--angle")) + 3) % 360;
boxElement.style.setProperty("--angle", `${angle}deg`);
requestAnimationFrame(updateAnimation);
};
requestAnimationFrame(updateAnimation);
}, []);
return (
<input
ref={boxRef}
style={{
"--angle": "0deg",
"--border-color": "linear-gradient(var(--angle), #111, #eee)",
"--bg-color": "linear-gradient(#111, #111)",
}}
placeholder="What do you want to do?"
className="my-8 flex w-60 items-center justify-center rounded-full border-2 border-slate-700/40 p-3 [background:padding-box_var(--bg-color),border-box_var(--border-color)] focus:outline-none text-slate-500"
></input>
);
};
Change this code from using linear-gradient to conic-gradient for the animation and give me a simple explanation
of what this code does.
import { useRef, useState, useEffect } from "react";
export const InputSpotlightBorder = () => {
const boxRef = useRef(null);
useEffect(() => {
const boxElement = boxRef.current;
if (!boxElement) {
return;
}
const updateAnimation = () => {
const angle =
(parseFloat(boxElement.style.getPropertyValue("--angle")) + 3) % 360;
boxElement.style.setProperty("--angle", `${angle}deg`);
requestAnimationFrame(updateAnimation);
};
requestAnimationFrame(updateAnimation);
}, []);
return (
<input
ref={boxRef}
style={{
"--angle": "0deg",
"--border-color": "conic-gradient(from var(--angle), #111, #eee)",
"--bg-color": "linear-gradient(#111, #111)",
}}
placeholder="What do you want to do?"
className="my-8 flex w-60 items-center justify-center rounded-full border-2 border-slate-700/40 p-3 [background:padding-box_var(--bg-color),border-box_var(--border-color)] focus:outline-none text-slate-500"
></input>
);
};
Explanation:
This code defines a custom input component called InputSpotlightBorder
, which creates an animated border effect using CSS gradients. The useRef
hook is used to reference the input
element, and the useEffect
hook is used to start the animation when the component is mounted.
The animation is created by updating the --angle
CSS variable in the boxElement
style. The updateAnimation
function is called repeatedly using requestAnimationFrame
to increment the angle by 3 degrees each time, creating a rotating effect.
The border-color
is set to a conic-gradient
instead of linear-gradient
to create a more circular border effect. The --angle
variable is used to animate the gradient, so that it rotates along with the border.
The --bg-color
is set to a linear-gradient
to create a solid background color for the input. The className
combines the background and border gradients using the background
property, and also sets some additional styles for the input element.