Displaying a relative div on mouse hover over an HTML tag using React

In the section below, you will find the code snippet...

<ul className="no-style board__list">
   {Object.keys(today.books).map(function(id) {
       var refBook = today.books[id][0];                                            
          return (
            <li key={refBook._id} className="board__list-item">
                <div className="container flexrow">
                      <div className="flexrow__fit-2">{refBook.book_no}</div>
                      <div className="flexrow__org">
                         <span className="board__icon-wrap">
                           {refBook.memo
                               ? (<i className="fa fa-flag" style={{color:"#F9AB9F"}}></i>)
                               : null
                           }
                        </span>
                           {refBooking.memo
                               ? (<div  className="memo_dialog">{refBook.memo}</div>)
                               : null
                           }
                     </div>
                </div>
           </li>
        );
    })}
</ul>

In my scenario, I possess an object named books array and my aim is to generate a fa-flag icon for each book. My objective is to display distinct memo dialog whenever hovering over each flag icon.

While I am familiar with implementing this using jQuery, I am seeking guidance on accomplishing the same in a React-based approach without relying on jQuery.

Answer №1

Are you unsure of the goal you are trying to achieve? This example could be beneficial for you:

class Book extends React.Component {
  constructor(props){
    super(props);
    this.handleOver = this.handleOver.bind(this);
  }
  handleOver(name){
    this.props.over(this.props.name)
  }
  render(){
    return <div onMouseOver={this.handleOver}>{this.props.name}</div>
  }
}

class BookList extends React.Component {
  constructor(props){
    super(props);
    this.mouseOver = this.mouseOver.bind(this);
    this.state = {
        books: ['hello', 'amazing', 'world'],
      memo: ''
    }
  }
  mouseOver(name){
    this.setState({memo: name})
  }
  render(){
    const bookList = this.state.books.map((book, index)=>{
        return <Book key={index} name={book} over={this.mouseOver}/>
    });
    return <div>
        {bookList}
      <hr/>
      <div>{this.state.memo}</div>
    </div>
  }
}

React.render(<BookList />, document.getElementById('container'));

Additionally, you can check out this fiddle example.

I hope this assists you. Thank you.

Answer №2

My recommendation is to utilize the state variable isHovered to store the state of the hover effect.

When isHovered is true, we display a component (in this case, a dialog box), and hide it when the variable is false.

Whenever we hover over the link element, the handleEnter function is triggered to set isHovered to true.

Conversely, when the cursor moves away from the link element, the handleLeave function is called to set isHovered to false.

For example:

class Test extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isHovered: false,
    };
  }

  handleEnter() {
    this.setState({
      isHovered: true 
    });
  }

  handleLeave() {
    this.setState({
      isHovered: false 
    });
  }

  render() {
    return (
      <div>
        <a
          onMouseEnter={this.handleEnter.bind(this)}
          onMouseLeave={this.handleLeave.bind(this)}
        >Link</a>
        {this.state.isHovered ? (
          <div className="box">A component</div>
        ) : (
          <div />
        )}
      </div>
    );
  }
}

For a demo, you can visit this CodePen link.

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

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

The Node Sass version 7.0.1 does not work with ^4.0.0 in React on Mac operating systems

Despite using what I believe to be the correct node, npm, and node-sass versions, I keep encountering the error message: "Node Sass version 7.0.1 is incompatible with ^4.0.0" when running the npm start command. I am perplexed by this 4.0.0 version, as it d ...

Are there any CSS attribute configurations that I am overlooking?

Reviewing a colleague's CSS file, I stumbled upon an interesting section. They are a skilled CSS designer, so before jumping to conclusions, I wanted to make sure I am not missing something. In the code snippet below, it seems like they are unintenti ...

Updating the parameter names in an AJAX request

Can the data parameters sent with AJAX be dynamically changed to a new name? For instance: let NewParamName = `Post_${incremented_value}`; $.post("index.php" { NewParamName : "someValue" }); Even after sending the request, the name in the parameters rem ...

The functionality of ng-style is not compatible with min, and utilizing ng-model produces undesirable results

Why does the ng-style condition not work with min=0 if the saved value of ng-model="detail.Amount" is negative? <input type="number" min="0" oninput="validity.valid||(value='');" class="form-control" title="Amount" ng-model="detail.Amount" ng ...

Include a search query parameter in the URL by adding "?search=" to connect with a

In my react/typescript application, I have a client and server setup. The client requests data from the server and displays it using React. When making a request for data on the client side, this is how it's done: export const createApiClient = (): A ...

The popover seems to be failing to appear

I am struggling to get a popover to appear when clicking on an appended href element dynamically. Here are the code snippets I have tried: <div id="myPopoverContent"> ...stuff... </div> <div id="div3" style= "width:200px;height:200px;" ...

The 'ReactNode' binding element is automatically assigned an 'any' type

Just started a new project using create-react-app app --template typescript. In the src/components/MyButton/MyButton.tsx file, I have the following code: import React, { ReactNode } from "react"; const MyButton = ({ children: ReactNode }) => ...

Can you assist me with setting a value in an ASP dropdownlist?

I have an asp dropdownlist and I need to set its value from the client side. Although I am able to retrieve the data from the client side, I am facing difficulty in setting it in my asp dropdownlist using JavaScript. HTML <div class="col-md-6 form-gro ...

An HTML form containing various input fields organized as a JSON string

I need to pass two parameters, param1 and param2, to a servlet. Param1 should be in JSON format, while param2 is a regular input value. param1 = {"id":"userid","name":"username","status":"userstatus"} param2 = add How can I accomplish this using the HTM ...

Node.js is having trouble locating the JSON file for Ajax requests

Currently, I've developed a fun little game using the p5.js library and wanted to integrate a Leaderboard feature that pulls data from a JSON file acting as a database to store Usernames and scores. To achieve this, I've utilized a Node.js server ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

Gracefully Switching Between Various Functions

Suppose I have a collection of functions that perform various tasks: function doSomething() { console.log('doing something'); } function accomplishTasks() { console.log('accomplishing tasks'); } function executeAction() { console. ...

Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document. This is my attempt to make the call: function httpGet(){ var theUrl = "https://lo ...

Bizarre CSS Transitions and Scaling Quirks in Webkit

Working on a website, you can check it out here In Chrome, some strange behavior occurs when the window reaches a certain resolution. Specifically, at 943 pixels width, white bars appear next to images when hovering over them, giving the impression that t ...

The textboxes are not displaying the floating numbers correctly

My issue involves 3 textareas with numbers displayed next to them. While I previously used a CSS table layout, it became inefficient when adding content between each row. I am puzzled as to why the second number, "2)", appears positioned next to the first ...

What could be causing the three.PointLightHelper to fail in my script?

I am encountering an issue with the line of code scene.add(new THREE.PointLightHelper(bluePoint, 3)); in my code snippet below: var bluePoint = new THREE.PointLight(0x0033ff, 100, 500); bluePoint.position.set( 500, -500, 25 ); scene.addLight(bluePoint); s ...

Creating PDF documentation in a JavaScript architecture MVC framework, specifically utilizing Backbone.js

In my project, I have implemented a Backbone Marionette single page application that interacts with a RESTful API backend using RoR. I am interested in providing users with the ability to export a PDF report that includes specific rendered views, regions, ...

Using the React Hook "usePathname" inside a callback is not allowed

Encountered an issue while deploying my Next.js application to Vercel. The process exits and throws an error message: "Error: React Hook "usePathname" cannot be called inside a callback. React Hooks must be called in a React function component or a custom ...

Can you explain the variance in these code snippets when implementing React's setState() function?

Can you explain the variance between these two blocks of code? this.setState((state)=>({ posts: state.posts.filter(post=> post.id !==postRemoved.id) })) versus this.setState((state)=>{ posts: state.post ...