Adjusting Screen Size for Lottie Animation in React.js

I need assistance with resizing a lottie animation component on my website's landing page to set its display to none on mobile devices. How can I achieve this?

See the lottie component code below:

import React from "react";
import Lottie from "react-lottie";
import data from "./Lottie/87736-car-animation.json";

export default function App() {
  const defaultOptions = {
loop: true,
autoplay: true,
animationData: data,
rendererSettings: {
  preserveAspectRatio: "xMidYMid slice",
    },
  };

  return (
<div id="lottie">
  <Lottie
    options={defaultOptions}
    height={800}
    width={1000}
    style={{
      top: "30%",
      right: "10%",
      zIndex: -1,
      overflow: "hidden",
      position: "fixed",
    }}
  />
</div>
  );
}

This is the home component:

import Lottie from "../Components/Lottie";
import React from "react";

function Landing () => {
  let width = window.innerWidth;
  if (width > 600px) {
console.log(width);
  } else {
document.getElementById("lottie").style.display = "none";
   }
  <Lottie className="col-lg-8 col-sm-12 lottie d-none" />
}

export default Landing;

I attempted using external CSS as well:

@media screen and (max-width: 600px) {
  .lottie {
display: none !important;
  }
}

Answer №1

When working with React, you have the ability to conditionally render components without resorting to native DOM manipulation methods like document.getElementById.

One way to simplify retrieving window size is by creating a reusable function:
Create a file named windowDimensions.js

export function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

Then import this function into your App component:

import React from "react";
import Lottie from "react-lottie";
import data from "./Lottie/87736-car-animation.json";
import {getWindowDimensions} from './windowDimensions.js';

function App() {
  const defaultOptions = {
    loop: true,
    autoplay: true,
    animationData: data,
    rendererSettings: {
      preserveAspectRatio: "xMidYMid slice",
    },
  };

  return (
    <div id="lottie">
      {/* Conditionally rendering the Lottie component based on window width */}
      { getWindowDimensions().width > 600 &&
        <Lottie
          options={defaultOptions}
          height={800}
          width={1000}
          style={{
            top: "30%",
            right: "10%",
            zIndex: -1,
            overflow: "hidden",
            position: "fixed",
          }}
        />
      }
    </div>
  );
}

export default App;

This code will only display the Lottie component if the window width exceeds 600 pixels. You could also consider using CSS conditional rendering with `visibility: hidden` in your media query. Be mindful of how you reference IDs and classes in your CSS to ensure proper styling.

It's recommended to review the classes applied to your Lottie component for any potential issues. Refer to React documentation on conditional rendering for further guidance.

Answer №2

The CSS you are applying will not affect your Lottie animation element because in your code, .lottie is a class while your Lottie element is defined with an id. Therefore, you should use #lottie instead:

@media screen and (max-width: 600px) {
  #lottie {
    display: none !important;
  }
}

Answer №3

When working with <Lottie />, simply remove the d-none class and replace it with

 d-lg-block d-md-block d-sm-none d-none
to get the desired result.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML does not support the use of certain symbols

Currently, I am in the process of designing a homepage for my school project. However, I have run into an issue. The content that I want to be displayed on my homepage is as follows: "Daudzspēlētāju tiešsaites lomu spēle (Massively Multiplayer Online ...

How can I dynamically populate my select field with JSON data using React.js?

My goal is to fetch data from an API and use the 'symbol' JSON field as options for a select dropdown. However, I'm encountering an issue: 'TypeError: Cannot read property 'length' of undefined.' Beneath my code, I' ...

Setting the dimensions of an HTML - CSS block

I am trying to style a navigation bar using the following CSS code: #nav {} #nav a { position: relative; display: inline-block; color: #F0F0F0; width: 1em; height: 2em; line-height: 0.9em; } #nav a.ic ...

My website is being cut off

After creating this website with a viewport setup, I noticed that it is not fully visible on certain screens. When viewed on a CRT monitor at 800x600 desktop resolution or lower than 1280x800, such as on mobile devices, the content gets clipped. Is there a ...

React-three - Showing a white square on Android mobiles in 3D model display

I am currently working on an innovative portfolio application utilizing Nextjs along with 3D libraries like Three and React-Three. For deployment, I rely on Vercel. A pressing issue has arisen where the 3D model in the deployed app is showing up as a bla ...

When I adjust the size of my browser, the elements on my HTML page shift around

I'm facing an issue where all my elements move when I resize my browser, and I cannot figure out why. How can I ensure that they stay in their respective positions even when the browser is resized? Is there a CSS solution for this? Thank you! body ...

What is the best way to create mock icons for all the React `@material-ui/icons` using Jest?

Can this query be broadened to ask - what is the best way to simulate all attributes on a module that has been imported in order to produce React components? ...

Creating diagonal background cutouts using CSS

Can you create a diagonal cut in a background color using CSS? Check out this example https://i.sstatic.net/vtpYf.jpg .item { color: #fff; font-size: 30px; background-color: #565453; padding: 10px 10px 10px 10px; width: 52%; text-align: ce ...

Create a jQuery animation that mimics the Safari home page experience. Create a

Is there a way to achieve a similar effect as Safari's new tab using HTML5 canvas instead of CSS3 3d transform? While we can create a similar transformation with CSS3 3D transform, it is limited to Webkit browsers. Can we use CANVAS to replicate this ...

Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn ...

The jQuery script version 3.5.1 encountered an error at line 4055 where DataTables was unable to access the property "aDataSort" due to it

Hey there, I'm currently facing a small challenge while trying to incorporate Datatables within a bootstrap modal to display the results of a SQL Server query. The main requirement is to provide the option to export the data as an Excel file or in oth ...

What is the best way to apply a semi-transparent background to my navigation bar, while maintaining a blue background across my entire page?

Currently, I have a background set for my website along with a navigation bar that displays my name and additional information. I am looking to make the background of this navigation bar semi-transparent so that it is possible to see through it. I tried ...

The issue arises when FormData is sending a request with no content when attempting to transfer

I am attempting to use FormData and Axios to send a form, but I am encountering issues. const formData = new FormData(); formData.append("title", title); formData.append("image", image); Axios.post("https://httpbin.org/anything&quo ...

Ensuring Data Population and Proper Display in React Testing Library - How to accurately verify that my provider is being filled with data and the child components are rendering correctly

In my scenario, I have a global app context where I need to store data retrieved from an endpoint. To achieve this, I am utilizing the useReducer hook. My approach involves calling an action named getIssuerDetails(), which dispatches various states and use ...

Whenever I attempt to start my ReactJS project using the command line with `npm run it`, I keep encountering an error

Encountered an issue with the webpack-dev-server script while working on my project. Ensure that your node.js and npm versions are up to date. If they are, the problem might lie within the reactjs package rather than npm itself. Kindly inform the author ab ...

Utilizing React with Ant Design to enable tag clicking and displaying in a text area

I am currently working on my React TypeScript project with Ant Design. One issue I am facing is that I want to be able to click on a tag and have it displayed in the text area. So, when I type some text, then click on a tag, followed by typing more text a ...

Display a preview of a React component

Currently facing a challenge where I need to create a form for users to adjust the title, background color, button background, text color, and other settings of a component. I want to provide a live preview of the component as the user makes changes. I en ...

Is it possible to showcase two modals on a single page, positioning one to the left and the other to the right using Bootstrap?

Can someone help me learn how to display two modals on the same screen, one on the left and one on the right? I am new to bootstrap and would appreciate some guidance! ...

Incorporate a fresh key-value pair into the Redux Toolkit's state

I am currently working on an application that enables users to create and modify recipes. To manage the state, I have chosen to utilize React Toolkit and Redux. Here is an example of the state structure: const ingredients = [ { ingredientName: &apos ...

Trying to utilize RegEx for my project, but feeling stuck on how to solve my problem

^\d{1,12}$|(?=^.{1,15}$)^\d+\.\d{1,2}$ This is the current regular expression I am using. I need to adjust the maximum limit to 100,000,000,000 with an option for two decimal places. Additionally, I would like users to be able to inpu ...