When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize my class names, or have any other clever way to create a flipcard in tsx?

./components/FlipCard/index.tsx

import { Container } from './styles';
import React from 'react';

function FlipCard() {
  const cardflip = document.querySelector('.cardflipper');
  cardflip.addEventListener('click', function () {
    cardflip.classList.toggle('is-flipped');
  });

  return (
    <Container>
      <div className="scene">
        <div className="cardflipper">
          <div className="card__face card__face--front">front</div>
          <div className="card__face card__face--back">back</div>
        </div>
      </div>
    </Container>
  );
}

export default FlipCard

./components/FlipCard/styled.ts

import styled from 'styled-components';

export const Container = styled.div`

.scene {
  width: 200px;
  height: 260px;
  border: 1px solid #CCC;
  margin: 40px 0;
  perspective: 600px;
}

.cardflipper {
  width: 100%;
  height: 100%;
  transition: transform 1s;
  transform-style: preserve-3d;
  cursor: pointer;
  position: relative;
}

.card.is-flipped {
  transform: translateX(-100%) rotateY(-180deg);
}

.card__face {
  position: absolute;
  width: 100%;
  height: 100%;
  line-height: 260px;
  color: white;
  text-align: center;
  font-weight: bold;
  font-size: 40px;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
}

.card__face--front {
  background: red;
}

.card__face--back {
  background: blue;
  transform: rotateY(180deg);
}
`;

Answer №1

Typescript is issuing a warning to remind you that when using querySelector, it may return null if the specified element does not exist.

To handle this warning, you can explicitly define the returning type as HTMLDivElement.

  const cardflip = document.querySelector('.cardflipper') as HTMLDivElement;

A more efficient approach would be to utilize template ref

import { Container } from './styles';
import React, { useRef, useEffect } from 'react';

function FlipCard() {
  const flippingCardRef = useRef()
  useEffect(() => {
    flippingCardRef.current.addEventListener('click', function() {
      flippingCardRef.current.classList.toggle('is-flipped');
    });
  });

  return (
    <Container>
      <div className="scene">
      <div className="cardflipper" ref={flippingCardRef}>
      <div className="card__face card__face--front">front</div>
      <div className="card__face card__face--back">back</div>
      </div>
      </div>
    </Container>
  );
}

export default FlipCard

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

JS: The values printed by setTimeout are always taken from the previous iteration

This issue I'm facing is directly related to JS scope, and despite my efforts in research, I have not been able to find effective solutions from similar stackoverflow queries. Here is the program in question: http://jsfiddle.net/0z525bhf/ function ...

"Encountering an error when trying to access undefined property in templates

The content displayed in my component template is not what I expected when using @Output to pass an object from a parent container. While attempting to bind {{selectedMovDetail|json}} in the template, the output shows as { "name": "The Walking Dead","rati ...

Having trouble with my AJAX request and can't figure out why. Anyone available to take a look and help out?

I have successfully implemented this AJAX script on various pages in the past without any issues. <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script& ...

Techniques for sending PHP variables to window.location using JavaScript

How can I successfully include a PHP variable in a JavaScript window.location function? The current code snippet below does not seem to be working for me. echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.&apos ...

What is the method for expanding this schema array using mongoose?

In the user schema below, I'm focusing on updating the ToDo section under User.js. My goal is to include new data to an array within the database. data.js app.post("/data", loggedIn, async (req, res) => { console.log(req.body.content); ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

The font appears bolder in Chrome once the CSS animation has finished

My CSS animation is causing some unexpected behavior on page load. Once the animation completes, the text suddenly appears thicker than intended, especially when it's a specific shade of red. Curiously, this strange "popping" effect only occurs with ...

"Opt for a horizontal WordPress drop-down menu instead of the typical vertical layout

I am looking to customize a menu in WordPress by creating a horizontal drop-down menu instead of the default vertical layout. An example of what I am aiming for can be seen on this website. If you hover over OUR SECTORS, you will see the type of menu I am ...

CSS slideshow animation is not functioning properly

Hey there, I'm new around here and I've got a question for you all. Please bear with me if I make any mistakes. So, I'm attempting to create a simple CSS slide image. In my animation code, I want the picture to fade from the left every time ...

retrieve webpage information with PHP

<?php $pullurl = 'http://akroncanton.craigslist.org/jjj/'; $contents = file_get_contents($pullurl); $result = preg_split('/<\/p>/',$contents); print_r($result); ?> After consulting with some individuals yesterda ...

How to retrieve the object's property with the highest numerical value using JavaScript

My current object is structured as follows: const obj = { happy: 0.6, neutral: 0.1, said: 0.3 } I'm trying to determine the best method to retrieve the property with the highest value (in this case, it would be "happy"). Any suggestions o ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

Issue with fixed positioning not behaving as intended while scrolling downwards

I am facing an issue with an element that has the .it class and I want to keep it fixed on the screen using the position: fixed CSS property. However, as I scroll down the page, the element moves along with the screen instead of staying in place. Below is ...

How to Filter Fields in AngularJS Based on a Start Date and End Date?

Hey everyone, I'm trying to filter items based on the start and end dates using the daterange functionality in my meanjs app. I've tried multiple approaches but haven't found a solution yet. If anyone knows how to do this, please help me out ...

I am experiencing difficulties with my bootstrap module not loading

Could you please investigate why my module isn't loading? The module is supposed to load under the specified conditions in the third last column, but when I test the code, it doesn't work. Can you assist me in identifying what might be causing th ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Currently working on a script using google-apps-script, open to any suggestions or ideas

Challenge: I am working on creating arrays to store values and iterate until a specific value is reached. Ultimately, this code will be used to match one letter to another, similar to how the WWII Bombe machine functioned, but in a purely digital format. T ...

The value of ng-repeat list in AngularJS does not update when its value is changed by an ajax call

I am completely perplexed. Why doesn't my ng-repeat update when there is an ajax call that changes its value? I have searched through many questions and answers here, but none of them address the issue with the ajax call. Here is the HTML: <div c ...

Comparison between Bootstrap 4 and Firefox Preload Error

Hello fellow front end developers who are experiencing an issue with CSS preload in Firefox versions above 74.0. I have encountered a problem with the following code snippet: <link rel='preload' as='style' onload="this.onload=null; ...

Hiding a column in jQuery DataTables

Can the jquery datatables plugin be used to easily hide and show a table column? I've successfully refreshed the table data by using fnClearTable and fnAddData. However, I'm facing a challenge in one of my table views where I need to hide certa ...