Is it possible to align the modal based on the mouse's position or a specific element?

Recently, I completed a React project that utilizes an API to search for movie titles. The project returns a list of movies corresponding to the user's search query. Everything seems to be working fine up to this point.

However, I encountered an issue with styling when it comes to displaying more detailed information about each movie in a modal. When I scroll down the list and click on a movie, the modal always opens at the top of the page.

I'm wondering how I can make each modal open based on the position of the mouse or the button element that was clicked.

Here is the CSS styling I have implemented so far:

.modal {
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: space-around;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.753);
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}

.inner-modal {
  text-align: left;
  background-color: rgb(255, 255, 255);
  color: black;
  width: 70%;
  height: auto;
  padding: 40px;
}

.modal-poster {
  float: right;
  width: 30%;
  padding: 20px 0 20px 30px;
}

Answer №1

To achieve this, JavaScript is your friend. Here's how you can do it:

1. Identify the target element

There are various methods to identify the target element. One way is to assign a data attribute to your Film element, like so:

<Film data-film-id={film.id} />

2. Calculate its position on the page

Record the clicked film's id in the state of your page component, and locate the clicked film element on the page using a useEffect.

  const [clickedFilmId, setClickedFilmId] = useState<string|null>(null)
  const [modalTopOffset, setModalTopOffset] = useState<number>(0)

  useEffect(() => {
    if (!clickedFilmId) {
      return
    }
    // find the element in the DOM using the data attribute set in step 1.
    const filmElement = document.querySelector(`[data-film-id='${clickedFilmId}']`) as HTMLElement | null
    // determine the element's distance from the top for the modal.
    setModalTopOffset(filmElement?.offsetTop ?? 0)
  }, [clickedFilmId])

3. Set the position of the Modal based on modalTopOffset

Create your own modal component or import one from a library. Here's an example of how it could be designed:

    <Modal
      {...otherModalProps}
      style={{
        position: 'absolute',
        left: '50%',
        transform: 'translateX(-50%)',
        // position the modal at the same offset as the clicked Film element.
        top: `${modalTopOffset}px`,
      }}
    >
      {children}
    </Modal>

You just need to add some additional styling in the code above to adjust the top position of the element, based on the modalTopOffset computed in the useEffect in step 2.

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

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

What's the best way to conceal the navbar while attempting to print the page?

Currently, I am working on developing an application for my school project. One of the features is an invoice sheet with a print option. However, when I try to print by clicking the button or using ctrl+p, the navbar appears in a chaotic and disorganized m ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

Having trouble accessing the property of undefined in material ui cards

Currently, I am incorporating Material UI cards into my React project. One issue I encountered is trying to implement two functions, onMouseOver and onMouseOut, in my cards. However, when I run the code, I receive an error message stating "Uncaught TypeE ...

What is the best way to ensure that a specified number of list items (li) will align properly within the width of an unordered list (ul

I'm attempting to make all the li elements' width match that of my ul element. Here is the code I am using: http://jsfiddle.net/4XR5V/2/ I have looked at some similar questions on the website and tried adding: ul { width: 100%; display: tab ...

In Firebase, doc.data() returns an object, not a string

I've been struggling with this error message for a while now: Error: Objects are not valid as a React child (found: object with keys {id, msg}). If you meant to render a collection of children, use an array instead. I finally found the issue here: us ...

Using an id as the attribute value for a React ref

I have a question about referencing DOM nodes in a component. Currently, I am able to get the nodes and children using the following code: export class AutoScrollTarget extends React.Component { constructor(props) { super(props); this ...

Tips for placing an element in the top left corner and turning it into a functional "back to top" button

I need to add a "back to top" button on my website and I want to place it in the top left corner, as shown in the image above. Here is the HTML code I am using in my Jekyll site: <body> <a name="top"></a> <a href="#top" id="to ...

What is the best way to incorporate an external SVG file into `SvgIcon` within material-ui?

Currently, I am integrating the SvgIcon component from material-ui into my React application. The examples provided in the documentation can be found at https://material-ui.com/api/svg-icon/ and all seem to use the <path d="M10 20v-6h4v6h5v-8h3L12 3 2 1 ...

Transform Default Buttons to Resemble Normal Buttons

I currently have a JavaFX button that is set as the Default Button, allowing users to select it with the Enter key. The button has a blue background: https://i.sstatic.net/SYvIj.png However, I would like to change its appearance to that of a normal butto ...

How to pass the Exact property in React MaterialUI Button with RouterLink Component?

I came across this code snippet: <Button activeClassName={classes.active} className={classes.button} component={RouterLink} exact={true} to="/app/certificates" > Certificates </Button> <Button activeClassName={classe ...

How to automatically reset a form after submission in React using Ant Design?

When using the antd template for form design, I encountered an issue where form input values were not getting cleared after submission. I attempted to use this.props.form.resetFields(), but it resulted in the following error: Unhandled Rejection (TypeErro ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

The component "react-native-snap-carousel" is having trouble displaying the card image

Recently, I started working with react native and encountered an issue while trying to implement the "react-native-snap-carousel". The carousel was functioning correctly with the data provided in the "carouselItems" array, but I faced difficulties with dis ...

Updating components in Next.js 13 application directory by syncing changes from server to client

I am experimenting with the new features in Next.js 13 within the app directory, and I aim to recreate certain functionalities that I currently have in the traditional pages directory. My goal is to showcase a grid of cards, each representing a different h ...

What is the best way to ensure that circles only touch each other by their edges?

Trying to align three circles touching each other has been a challenge for me. Although I have successfully managed to make two touch, the third one remains elusive. How can I ensure that all three circles are in contact with each other, especially when th ...

It is impossible to adjust the padding of Material UI buttons

No matter what pixel value I choose, nothing seems to happen. The only time I see a change is when I adjust either the paddingLeft or paddingRight parameter. Even then, if I try to set both paddings, nothing happens. It's as if the trick only works wh ...

Webster Barron code script

I'm attempting to replicate the concept of this video https://www.superhi.com/video/barron-webster using text, but I am encountering difficulties in achieving the desired effect. The design text is currently overlapping my name and displaying in rev ...

Integrate your React Native application with a Node.js backend on your local machine

My attempt to establish a connection between my react native app and my node.js app on a Windows system has hit a roadblock. While I am able to receive responses from the node API using Postman, the response from the react native app is coming back as unde ...

What is the best way to execute a code once another has successfully completed its run?

Within milliseconds, I am required to update a JSON file with new data and then fetch that updated information. However, after posting the data into the JSON file, it appears that when attempting to retrieve it, the old data is returned instead of the newl ...