Create a dynamic menu dropdown with absolute positioning using React

I recently made the transition to React and now I am in the process of converting my old vanillaJS website into ReactJS.

One issue I am facing is with a button that is supposed to trigger the opening of a dropdown menu.

<button 
   type="button" 
   onClick={() => setMenuOpen(!isMenuOpen)} 
   ref={menuBtn}>menu</button>

Further down in the DOM structure, I have:

{
isMenuOpen ?
  <nav style={{
     top: menuBtn.current.offset().top + menuBtn.current.outerHeight(),
     left: menuBtn.current.offset().left + (menuBtn.current.outerWidth() / 2)
  }}>
    ...
  </nav>
: null
            }

In addition to this, I have the following code snippet:

const [isMenuOpen, setMenuOpen] = useState(false)
let menuBtn = React.createRef()

placed at the beginning of my function Component.

However, despite implementing all these changes, the functionality does not work as intended.

The error message I receive is:

TypeError: Cannot read property 'offset' of null

Moreover, I believe that even if this issue was resolved, it would not be responsive. As when the user clicks on the button and then resizes the window, the menu will not adjust accordingly to the new position of the button.

Your assistance is greatly appreciated!

Answer №1

The solution involved utilizing .current.getBoundingClientRect() instead of using .current.offset()

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

Issue with Deploying a Fresh React Application - Is the problem with HTML or index.js?

Welcome, esteemed guests. Today marks the launch of my very first React web app portfolio as I step into the domain of potential employers. However, I have encountered a hurdle in creating an optimized production build that has left me with the message &ap ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

Challenges faced with meta tags while integrating redux-persist into Next.js

I'm currently developing an e-commerce application using Next.js and redux. One challenge I've run into is that when I integrate redux-persist into the app, all meta tags cease to function properly. Below are snippets of the code I am working wit ...

Is there a way to automatically update the URL to include $_GET['data'] (media.php?data=123) when a selection is made from a dropdown list?

I'm currently working on a project that involves a website in PHP and a MySQL database. I have successfully linked the two together, and now I have a combobox filled with data from the database. Below is my script for handling the selection: <scr ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

Having trouble with exporting static HTML using Next.js

Recently, I have completed a project and now I am looking to export it to static HTML. In order to achieve this, I added the following command in my package.json file: build" : "next build && next export Upon running the command npm run ...

Detecting mistakes using ES6 assurances and BookshelfJS

I'm working on implementing a simple login method for a Bookshelf User model in an ExpressJS application. However, I am facing issues with handling errors from the rejected promises returned by the login function in the User model. While referring to ...

Building a matrix of checkboxes

I am looking to design a grid of checkboxes that are displayed in columns, with 5 checkboxes in each column. <ul class="checkbox-grid"> <li><input type="checkbox" name="text1" value="value1" /><label for="text1">Text 1</lab ...

Preserving the original "this" context while binding a callback for a React child

class Parent extends React.Component { constructor(props) { super(props) this.handleChildOnClick = this.handleChildOnClick.bind(this) } handleChildOnClick() { /* Here, I want to perform an action that involves both Child and Parent. ...

NextJS stores user information and token (obtained from an external API) for both client-side and server-side components

I am currently developing a fresh web application in NextJS, incorporating both client-side and server-side components. The user data is being transmitted to an API that already exists (.NET). My task is to store the details of the logged-in user such as t ...

Ways to reload an independent page in order to access PHP session variables:

Starting off, I want to mention that my approach may not be the most efficient. As a novice in JavaScript and PHP, I am aware that there are better and simpler ways to achieve what I'm attempting. The issue seems to be related to session variables an ...

What causes the closure variable to be reset after iterating over JSON data using $.each method?

Take a look at this scenario: var elements = []; $.getJSON(data_url, function(result) { $.each(result, function(key, value) { elements.push(parser.read(value.data)); // at this point, "elements" contains items }); }); dataLayer.addElements( ...

Import next.js API endpoint directly within the getServerSideProps function

When utilizing getServerSideProps() in Next.js to fetch data, it is advised to directly import the API endpoint rather than using fetch() and triggering another HTTP request. I successfully implemented this approach until incorporating middleware for my AP ...

Troubleshooting problem with infinite scrolling in AngularJS with Ionic framework

I recently created a webpage with an infinite scroll page load more script using Ionic AngularJS. However, I encountered an issue where the page restarts from the beginning once it reaches the bottom. Below is the HTML code snippet: <ion-content class ...

A guide on utilizing the context API consumer within the getInitialProps function of Next.js

Is there a way to incorporate the context API within getInitialProps in order to manage the loading spinner while making requests? What is the best approach to invoke my context methods within getInitialProps function? ...

Turn off server-side rendering to utilize useMediaQuery in Next.js

Next.js 13 responsiveness issue I am looking to implement the useMediaQuery function import { useMediaQuery } from 'react-responsive' Encountering a hydration error which is discussed in this post (Hydration failed with react-responsive generat ...

Having trouble getting a value from a textbox to PHP using jQuery - can anyone lend a hand?

<script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script> <input type="text" id= ...

Utilizing ReactJS to dynamically fetch images via API

I am currently working on loading images from an API to my client app. One idea I had was to save the images in a folder and store the image path in the database, rather than storing the actual image in the database itself. However, I have encountered diff ...

Encountering an error while trying to install material-ui for React

Encountering an error during the installation of material-ui error Darwin 16.7.0 error argv "/Users/xyz/.nvm/versions/node/v7.5.0/bin/node" "/Users/xyz/.nvm/versions/node/v7.5.0/bin/npm" "install" "material-ui" 34 error node v7.5.0 35 error npm v4.1 ...

Utilize the Material UI SelectField component as a reference for handling onChange events

I'm facing a challenge with my form that contains over 15 SelectField components. I want to avoid creating multiple change handler functions, but I can't figure out how to identify the specific select field that triggered the change event in orde ...