Home » How to Construct a Marquee Component with React

How to Construct a Marquee Component with React

by Icecream
0 comment

When you consider marquees, you typically envision the colourful lights and spinning shows at amusement parks, bringing again fond reminiscences of your childhood.

Similarly in net purposes, marquees inject a vigorous visible sense by effortlessly grabbing consideration and infusing your on-line tasks with dynamism.

Join me as we discover the way to construct an interesting marquee element in React.
This step-by-step information targets everybody no matter talent stage, we purpose to make your expertise with React each fulfilling and helpful.

What We’ll Cover:

  1. Understanding Marquee Components
  2. Benefits of Marquees
  3. Planning and Designing the Marquee Component
  4. How to Implement the Marquee Component
  5. How to Enhance the Marquee Component
  6. Best Practices and Tips for Marquee Component Development
  7. Conclusion

Prerequisites

  • Fundamentals of HTML and CSS
  • Fundamentals of ES6 JavaScript and React

Understanding Marquee Components

A marquee represents a steady part of textual content or visible content material (resembling footage) that scrolls routinely in a horizontal path.

Although the official HTML Marquee aspect is out of date and its use is closely discouraged, the idea of scrolling, limitless parts so as to add zest to a webpage continues to be very a lot in use, and could be discovered on quite a few trendy web sites.

This impact is realized by means of CSS animations, providing a extra environment friendly, fluid, and light-weight animation consequence.

A visible instance of a marquee element from Webflow is proven beneath.

00-Example-marquee
Webflow Example

Benefits of Marquees

They have a bunch of usefulness resembling:

  • Attention-grabbing: Marquees are glorious for drawing consideration to particular content material on a webpage. Whether it is a particular supply, announcement, or featured content material, a transferring marquee naturally catches the attention.
  • Visual Appeal: Adding a contact of movement to your web site enhances its visible attraction. Marquees can carry life to a web page, making it extra dynamic and interesting for customers.
  • Highlighting Important Information: When you wish to emphasize important data like breaking information, upcoming occasions, or pressing messages, a marquee is an efficient manner to make sure that customers do not miss out.
  • Event Promotion: They are notably helpful for selling occasions or time-sensitive actions. Their scrolling nature lets you show occasion particulars, dates, and highlights space-efficiently.
  • Ticker-Style Updates: For displaying real-time updates, resembling inventory costs, information headlines, or social media feeds, marquees present a ticker-style format that retains data constantly flowing for customers.
  • Interactive Banners: They can function interactive banners, permitting customers to click on on particular gadgets as they scroll by. This could be a inventive technique to lead customers to totally different sections or pages of your web site.
  • Dynamic Product Showcases: E-commerce web sites can profit from marquees by showcasing new merchandise or featured gadgets in a visually participating manner, encouraging customers to discover the choices.
  • Call-to-Action Emphasis: If you could have particular call-to-action messages, utilizing them can provide prominence and be certain that they do not go unnoticed.
  • Breaking Monotony: In lengthy pages or static content material, a well-designed marquee can break the monotony and add a component of shock, making the consumer expertise extra attention-grabbing.
  • Versatility: They are versatile and could be personalized to swimsuit numerous types and themes, making them a versatile software for net designers searching for to create distinctive and memorable consumer interfaces.

Planning and Designing the Marquee Component

Before you begin coding, it is essential to plan and design your element and contemplate components resembling:

  • Define Content: Clearly define the content material you wish to show within the element. This might embody textual content, photos, or a mix of each.
  • Scroll Speed: Determine the specified scrolling velocity for use. Consider the optimum tempo for readability and visible attraction.
  • Visual Design: Sketch or visualize the way you need it to look. Decide on colours, fonts, and any further styling to align together with your total design scheme.
  • Behavior at Scroll End: Consider its conduct when it reaches the top of its scroll place. Decide whether or not it ought to loop constantly, bounce backwards and forwards, or have a selected end-state.
  • User Interaction: If relevant, plan for any consumer interplay. This might embody pausing on hover or permitting customers to click on on gadgets throughout the marquee.
  • Responsive Design: Ensure that your element is designed to be responsive, adapting seamlessly to totally different display screen sizes and units.
  • Testing Considerations: Anticipate potential challenges or changes wanted throughout the testing section. Plan for the way it will behave on numerous browsers and units.
  • Accessibility: Keep accessibility in thoughts, guaranteeing that customers with totally different disabilities can nonetheless entry and perceive the content material inside it.

How to Implement the Marquee Component

To implement the element, begin by making a React setting with Vite.

npm create vite@newest

After which you navigate to your undertaking listing, set up the required packages and begin up the dev server.

01-react-server-after-installation-
Setting up dev server

Next, create the weather for the JSX mockup to your element.

export default perform App() {
  return (
    <div className=" main__container">
      <h1>My Marquee</h1>
      <part className=" ">
        <h2>Default Behaviour</h2>

        <div className="marquee">
          <ul className="marquee__content">
            <div className=" marquee__item">
              <img src={AndroidLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={BehanceLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={GoogleLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={InstagramLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={PaypalLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={SpotifyLogo} alt="" />
            </div>
          </ul>

          <ul aria-hidden="true" className="marquee__content">
            <div className=" marquee__item">
              <img src={AndroidLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={BehanceLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={GoogleLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={InstagramLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={PaypalLogo} alt="" />
            </div>
            <div className=" marquee__item">
              <img src={SpotifyLogo} alt="" />
            </div>
          </ul>
        </div>
      </part>
    </div>
  );
}

This features a header for the element, the conduct of the element and the info within the element to be animated.

It is essential to duplicate the info within the element as it will be used to realize the duplicate impact. However, we’re hiding the second listing initially utilizing the aria-hidden='true' property.

To make it extra visually interesting, add these types.

physique {
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
    Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  padding: 2rem;
  width: 100%;
  min-height: 100vh;
  font-size: 1rem;
  line-height: 1.5;
}

* { box-sizing: border-box; }

h1 {
  font-size: 2rem;
  font-weight: 600;
  line-height: 1.2;
  margin-block: 2rem 1rem;
  text-align: middle;
}

h2 {
  font-size: 1.25rem;
  font-weight: 600;
}

part { margin-block: 3rem; }

.main__container {
  max-width: 1000px;
  margin-inline: auto;
  background: rgb(124, 145, 175);
  padding: 3rem;
}

/* Marquee types */
.marquee {
  --gap: 1rem;
  place: relative;
  show: flex;
  overflow: hidden;
  user-select: none;
  hole: var(--gap);
  border: 2px dashed lightgray;
}

.marquee__content {
  flex-shrink: 0;
  show: flex;
  justify-content: space-around;
  hole: var(--gap);
  min-width: 100%;
}

.marquee__content img {
  max-width: 2rem;
  width: 100%;
  object-fit: comprise;
}

.marquee__content > * {
  flex: 0 0 auto;
  coloration: white;
  background: #e8daef;
  margin: 2px;
  padding: 1rem 2rem;
  border-radius: 0.25rem;
  text-align: middle;
}

.marquee__item {
  show: flex;
  justify-content: middle;
  align-items: middle;
}

ul { padding-left: 0; }

At the second, your element ought to appear to be this;

02-UI-after-applying-styles
UI after making use of types

To animate this element, begin by defining customized CSS keyframes.

@keyframes scroll {
  from { remodel: translateX(0); }
  to { remodel: translateX(calc(-100% - var(--gap))); }
}

Note: The hole used is similar hole between the marquee gadgets.
Then, assign these keyframes to a category.

/* Enable animation */
.enable-animation .marquee__content {
  animation: scroll 10s linear infinite;
}

Finally, add that class to your part aspect.

<part className="enable-animation">

And with that, your element ought to already be animating.

03-Animated-marquee
Animated marquee

How to Enhance the Marquee Component

This element goes past the common infinite animations (as proven above), it typically possess some further functionalities resembling:

  • Pause on Hover: While utilizing a marquee could be helpful to indicate a bunch of content material extra dynamically, the velocity of the animation or the place of the data related to the consumer may trigger points, particularly for gradual readers.

To repair this, you possibly can implement a pause performance to halt it when the consumer hovers over it. Just add the CSS code beneath.

/* Pause on hover */
.marquee:hover .marquee__content {
  animation-play-state: paused;
}

And with that, it pauses on hover.

04-Animated-marquee-that-pauses-on-hover
Animated marquee that pauses on hover
  • Reverse on Double Tap: In the case the place a consumer has handed essential data and desires to see it with out ready for the looping animation to carry it again, it’s essential to supply a method to realize that.

By double tapping on the element, the animation performs in the other way, exhibiting the data the consumer simply handed. This function not solely promotes accessibility but in addition provides your net pages a handy guide a rough really feel, because it gives a faster technique to get data.

To implement this, begin by making a reverse animation state.

 const [reverseAnimation, setReverseAnimation] = useState(false);

The create a perform to flip the state of the animation.

const deal withDoubleClick = () => {
    setReverseAnimation((prev) => !prev);
  };

After that, create the CSS class rule to reverse the animation.

/* Reverse animation */
.marquee--reverse .marquee__content {
  animation-direction: reverse !essential;
}

Then connect the handler perform to the element.

<div className="marquee" onDoubleClick={deal withDoubleClick}>
      <ul className="marquee__content">
        <div className=" marquee__item">
          <img src={AndroidLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={BehanceLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={GoogleLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={InstagramLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={PaypalLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={SpotifyLogo} alt="" />
        </div>
      </ul>

      <ul aria-hidden="true" className="marquee__content">
        <div className=" marquee__item">
          <img src={AndroidLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={BehanceLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={GoogleLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={InstagramLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={PaypalLogo} alt="" />
        </div>
        <div className=" marquee__item">
          <img src={SpotifyLogo} alt="" />
        </div>
      </ul>
</div>

Finally, conditionally add the reverse class to the element which reverses the animation on double click on.

 <div className={`marquee ${reverseAnimation && "marquee--reverse"}`} 
      onDoubleClick={deal withDoubleClick}>

Double-clicking the element now provides;

05-Animated-marquee-that-revereses-on-double-click
Animated marquee that reverses on double click on
  • Pause/Play on Space Bar Click: Another performance that may be added to enhance UX, particularly for keyboard customers is to pause or play it on press of the spacebar. This mimics the performance of how movies work on the internet and would assist enhance accessibility for customers.

To implement this, begin by making a state to retailer the present paused state of the animation.

const [isAnimationPaused, setIsAnimationPaused] = useState(false);

Then create the CSS rule for the paused state.

/* Pause animation */
.marquee--paused .marquee__content {
  animation-play-state: paused !essential;
}

After that, create an impact that updates the isAnimationPaused state every time the area bar is pressed.

 useEffect(() => {
    const handleKeyPress = (occasion) => {
      if (occasion.code === "Space") {
     
        setIsAnimationPaused((prev) => !prev);
      }
    };
    doc.addEventListener("keydown", handleKeyPress);

   // Clean-up perform when element unmounts
    return () => {
      doc.take awayEventListener("keydown", handleKeyPress);
    };
  }, []);

This manner, the state toggles between true and false primarily based on consumer presses.
Finally, dynamically add the paused class to your element.

<div className={`marquee ${reverseAnimation && "marquee--reverse"} ${
       isAnimationPaused && "marquee--paused"}`} onDoubleClick={deal withDoubleClick}>

And with that, your element pauses and replays every time you press the area bar.

06-Animated-marquee-that-can-be-paused-with-space-bar
Animated marquee that may be paused with area bar

Best Practices and Tips for Marquee Component Development

Some of the most effective practices to think about when constructing this element contains:

  • Lazy Loading Images: In the case the place your marquee has a variety of high-quality photos which might be massive, it’s important to optimize them earlier than constructing the element.
    Lazy loading defers the browser from downloading the pictures till they’re wanted (required to be proven within the viewport), reducing down on total web page load time.

To obtain this, add loading='lazy' property to your photos.

<ul className="marquee__content">
    <div className=" marquee__item">
      <img src={AndroidLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={BehanceLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={GoogleLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={InstagramLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={PaypalLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={SpotifyLogo} alt="" loading="lazy" />
    </div>
  </ul>

  <ul aria-hidden="true" className="marquee__content">
    <div className=" marquee__item">
      <img src={AndroidLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={BehanceLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={GoogleLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={InstagramLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={PaypalLogo} alt="" loading="lazy" />
    </div>
    <div className=" marquee__item">
      <img src={SpotifyLogo} alt="" loading="lazy" />
    </div>
</ul>

  • Mindful Animation Speed: When implementing the animation, it is essential to strike a cautious steadiness when it comes to velocity. The animation tempo ought to be visually interesting, capturing the consumer’s consideration with out sacrificing readability or inflicting discomfort.
    This includes considerate consideration of how shortly the content material scrolls throughout the display screen.
    By taking note of animation velocity and discovering the best steadiness, you improve the general consumer expertise, making it an efficient and fulfilling aspect in your web site.
  • Think of Users with Motion Sensitivity: Inclusive design means bearing in mind the wants and preferences of various customers, together with these with movement sensitivity. Certain customers might desire much less motion as a consequence of circumstances resembling vestibular problems or just for private consolation.
    To help these customers, you should utilize the prefers-reduced-motion media question in your element.

/* Pause animation when reduced-motion is about */
@media (prefers-reduced-motion: scale back) {
  .marquee__content {
    animation-play-state: paused !essential;
  }
}

  • Proper Documentation: Provide clear documentation on how customers can use your element successfully in order that they will not wrestle to make use of it or don’t miss out on the all of the options it has. Consider utilizing labels across the element or a pop-up to convey brief directions on its use.

Conclusion

Your information to React Marquee Components is full! From planning to execution, you have dived into creating dynamic scrolling parts to your net tasks.

Remember, this element is greater than movement—it is an interactive story. Whether sharing essential data, selling occasions, or injecting dynamism, your marquee is a flexible addition to your toolkit.

But this journey is only the start. Adjust speeds, contemplate sensitivities, and undertake finest practices to refine your marquee. Let creativity circulate, and will your scrolling tales depart a long-lasting affect.

Prioritize consumer expertise, experiment with enhancements, and let your growth shine within the net panorama. Happy scrolling!

Contact Information

Want to attach or contact me? Feel free to hit me up on the next:

You may also like

Leave a Comment