Heading.js 1.78 KB
import React, { useRef } from "react";
import { motion, useInView } from "framer-motion";

const splitText = (text) =>
  (text || "").toString().split("").map((char, index) => ({
    char,
    key: `${char}-${index}`,
  }));

const Heading = ({
  el: Wrapper = "h2",
  subheading = "",
  heading = [],
  className = "",
}) => {
  const headingArray = Array.isArray(heading) ? heading : [heading];

  const headingVariants = {
    hidden: { opacity: 0.2, y: 0 },
    visible: (i) => ({
      opacity: 1,
      y: 0,
      transition: {
        delay: i * 0.05,
      },
    }),
  };

  return (
    <div className={`headings mb-3 ${className}`}>
      <Wrapper className="subheading">{subheading}</Wrapper>
      <div className="heading-container">
        {headingArray.length > 0 &&
          headingArray.map((item, index) => (
            <InViewWrapper key={index}>
              {splitText(item).map((char, i) => (
                <motion.span
                  key={char.key}
                  custom={i}
                  initial="hidden"
                  animate="visible"
                  variants={headingVariants}
                  className="heading"
                  style={{ display: "inline-block" }} // No whiteSpace or word-wrap styles here
                >
                  {char.char === " " ? "\u00A0" : char.char}
                </motion.span>
              ))}
            </InViewWrapper>
          ))}
      </div>
    </div>
  );
};

const InViewWrapper = ({ children }) => {
  const ref = useRef(null);
  const isInView = useInView(ref, { triggerOnce: true, threshold: 0.1 });

  return (
    <div ref={ref}>
      {React.Children.map(children, (child) =>
        React.cloneElement(child, { animate: isInView ? "visible" : "hidden" })
      )}
    </div>
  );
};

export default Heading;