Is it possible to enable tab navigation for a button located within a div when the div is in focus?

I have a component set up like this: (Check out the Code Sandbox example here: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js) https://i.sstatic.net/ZuxdL.png

The section highlighted in green is a div. Here is the code snippet:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [insideApp, setInsideApp] = useState(false);
  return (
    <div onFocus={() => setInsideApp(true)} onBlur={() => setInsideApp(false)}>
      <div className="App">
        <input className="input" />
        {insideApp && <button>Show Button</button>}
      </div>
      <p>Out of Box content</p>
    </div>
  );
}

/* css */
.App {
  display: flex;
  border: 2px solid aqua;
  align-items: center;
  column-gap: 2vw;
  padding: 2rem;
}

.App:focus-within {
  border: 2px solid lime;
}

.input {
  flex: auto;
}

My goal is to highlight the button when navigating with the tab key, as shown below:

https://i.sstatic.net/EXCWB.png

However, because I am conditionally rendering the button, I lose focus. Can someone provide an innovative solution to achieve the desired behavior? I want the div to change to lime color when focused and ensure that both input and button are accessible through tab navigation.

Additionally, I only want the button to be displayed when the focus is within the div.

Answer №1

If you want to simplify the process, you can achieve it using only CSS:

import { useState } from "react";
import "./styles.css";

export default function App() {
  // const [insideApp, setInsideApp] = useState(false);
  return (
    <div>
      <div
        className="App">
        <input className="input" />
        <button>Show Button</button>
      </div>
      <p>Out of Box content</p>
    </div>
  );
}

CSS:

.App {
  display: flex;
  border: 2px solid aqua;
  align-items: center;
  column-gap: 2vw;
  padding: 2rem;
}

.App:focus-within {
  border: 2px solid lime;
}

.App button {
  display: none;
  pointer-events: none;
}

.App:focus-within button {
  display: flex;
  pointer-events: auto;
}

.input {
  flex: auto;
}

Here's how it works:

  1. The :focus-within pseudo-class is used to show or hide the button based on focus
  2. The button element initially has no cursor events and remains hidden by default to prevent interactions
  3. When the parent container is focused within, the button becomes visible and interactive

Answer №2

Check out SyntheticEvents by visiting https://reactjs.org/docs/events.html

You can utilize the events onMouseEnter and onMouseLeave to highlight the div and hide the button.

<div
      onMouseEnter={() => setInsideApp(true)}
      onMouseLeave={() => setInsideApp(false)}
    >
      <div className="App">
        {insideApp ? (
          <div>
            <input className="input" />

            <button>Hide Button</button>
          </div>
        ) : null}
      </div>
      <p>Additional content here</p>
    </div>

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

Why does Heroku keep saying it cannot locate the package.json file in my module every time I attempt to do a heroku push?

After creating my own npm package by forking react-coverflow, everything seemed to work perfectly when using it locally in my app with the command "npm install react-coverflow-mod" --save. I was able to run my app smoothly by selecting "run with debug (F5 ...

When employing Flatlist, an issue arises where the image fails to appear on the screen, accompanied by an error message stating "value for uri cannot be cast from Double to String."

I'm facing an issue with displaying images in my flatlist. The error message I receive is "Error while updating property 'src' of a view managed by : RTCImageView." Can anyone help me identify what might be causing this problem in my code? ...

jQuery slideToggle function not working properly when clicking on a link within a div

I am facing a slight issue with the slideToggle function when there is a link inside the slideup panel. My goal is to create a button that, when clicked, will slide up a div displaying related posts. Subsequently, when another button or project link is cli ...

Stop iPhone body scrolling when fullscreen overlay is opened

My goal is to prevent the body from scrolling when my fullscreen overlay navigation is open. I have added a class show-nav to the body with the CSS attribute overflow: hidden, which works perfectly on desktop but not on iPhones. After researching similar ...

Changing the appearance of a radio button dynamically upon clicking

I am currently working on a dynamic pickup date form that utilizes radio buttons. My goal is to change the style of the selected value when a user clicks on it. Below is the code I have tried, but it has not been successful: foreach ($period as $day){ ech ...

The Google Maps marker is not accurately displaying the designated location

While working on my project, I successfully integrated Google Maps. However, I have encountered a problem: when I search for a specific location, the marker is not displaying at the correct point, but rather somewhere else. The latitude and longitude value ...

Using act() in React/Jest/MSW causes errors when waiting for a response

As I delve into learning how to unit test with React, my focus has shifted towards using TypeScript. Unfortunately, the course I am taking does not cover most errors related to TypeScript. In my testing journey, I have set up a simple testing function with ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Sass encountered an issue when trying to import using the "~" symbol from the node_modules directory

I am currently developing a single-page web application using Angular 6, and I recently integrated the ngx-toast library into my project. However, I encountered an issue when trying to load the libraries by adding the following Sass code with the "~" symb ...

Ways to programmatically append data to an object using JavaScript

My dilemma involves an object: var myObject={}; accompanied by a function that appends values to the object: function appendData(id, name){ //logic to validate id and name format, specify conditions for name being "John" and id being "I23423" my ...

Leveraging the power of ExpressJs to incorporate a dynamic Navbar onto

ExpressJS and EJS are my chosen technologies for creating Views. When it comes to the navigation bar, I want to add a class="active" to the links that represent the current page. However, if I use partials in my views, how can I achieve this? Here is a q ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Tips for preserving a circular element shape while accommodating dynamic content

I'm attempting to generate a circular shape using the ::after pseudo element, which adjusts its size automatically based on the content inside. .container { display: flex; flex-direction: row; } #dividerHost2 #left { flex: 1 1 auto; ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

Tips for utilizing revalidatePath feature in Next.js v13

Currently diving into the world of nextJs13, I'm a bit puzzled by the functionality of revalidatePath. Can someone please clarify how to utilize revalidatePath? Is it a function or perhaps a GET endpoint? I have two separate pages and when I make ch ...

Exploring the values of a JavaScript promise while iterating through a for loop

I find myself wandering in the land of possibilities and would greatly appreciate some direction. After spending 2-3 hours scouring through countless SO questions and documentation related to my current predicament, I still seem to be missing the mark. Ove ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

Retrieve the data stored in a selection of checkbox fields on a form

I have a table of checkboxes: <div> <h1 class="text-center">Select activities</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Link activ ...

Retrieve State from Store in Routing Configuration File [using react-router v4 and redux-thunk]

I'm currently in the process of creating a ReactJS web application (still learning the ropes). In my project, I am making use of react-router v4 and redux-thunk. I'm seeking guidance on how to retrieve the current state value from my store withi ...

Angular array mapping techniques

My JSON Object $scope.selectedItems ={ "RECORDS": [ { "Id": 23040035705987, "arriveddate": "2015/04/24", "expirationDate": null, "replacedDate": null, "processDate": "2015/04/24" ...