Identify the element with the active class name as the primary focus

Can anyone assist with this issue? Below is an example of the code I am working with:

import React, { useRef, useEffect } from "react";

function App() {
  const inputRef = useRef(null);

  useEffect(() => {
    const testElement = document.querySelectorAll(".active");
    testElement.length > 0 && inputRef.current.focus();
   }, []);

  return (
    <div style={{width: 200, height: 190, display: "flex", flexDirection: "column", justifyContent: "space-between"}}>
      <input id={1} type="text" ref={inputRef} />
      <input id={2} type="text" ref={inputRef} />
      <input id={3} className={"active"} type="text" ref={inputRef} />
      <input id={4} type="text" ref={inputRef} />    
    </div>
  );
}

export default App;

I am facing a challenge in focusing on a specific element that has a particular class name. In this case, the element is an input field with the id "3" and a class name of "active". However, the focus is currently being set to the input element with id "4" instead.

Your help is greatly appreciated.

Answer №1

In React, it's best practice to control the .active class by updating the state/properties. Whether it's through an action like a click event or directly changing the state, the focus can also be controlled (as shown in the 3rd example). It's important to avoid direct DOM manipulation.

If multiple elements share the same ref and they replace each other during renders, only the last item will receive focus. To address this with refs, you should use an array for inputRef and have each input add itself to the array using a function ref.

You can then iterate through the items in a useEffect hook, find the one with the .active class, and set focus on it.

const { useRef, useEffect } = React;
function App() {
  const inputRef = useRef([]);
  useEffect(() => {
    for(const r of inputRef.current) {
      if(r.classList.contains('active')) {
        r.focus();
        return;
      }
    }
   }, []);
   const addRef = r => inputRef.current.push(r)
  return (
    <div style={{width: 200, height: 190, display: "flex", flexDirection: "column", justifyContent: "space-between"}}>
      <input id={1} type="text" ref={addRef} />
      <input id={2} type="text" ref={addRef} />
      <input id={3} className={"active"} type="text" ref={addRef} />
      <input id={4} type="text" ref={addRef} />    
    </div>
  );
};
ReactDOM.render(
  <App />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

Alternatively, if you're already manipulating the DOM, you can directly use document.querySelector(). While not the recommended React approach, it is simpler and doesn't require refs:

const { useEffect } = React;

function App() {
  useEffect(() => {
    const active = document.querySelector('.active');
    
    if(active) active.focus();
   }, []);

  return (
    <div style={{width: 200, height: 190, display: "flex", flexDirection: "column", justifyContent: "space-between"}}>
      <input id={1} type="text" />
      <input id={2} type="text" />
      <input id={3} className={"active"} type="text" />
      <input id={4} type="text" />    
    </div>
  );
};
ReactDOM.render(
  <App />,
  root
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>

If you're working with a model passed via state/props, you can utilize the state/properties to manage focus and class (see comments in the code):

const { useRef, useEffect } = React;
// Each item renders it's own input, and focuses the item if the selected prop is true
const Item = ({ selected }) => {
  const inputRef = useRef(null);
  useEffect(() => {
    if(selected) inputRef.current.focus();
  }, [selected]);
    
  return (
    <input className={selected ? 'active' : ''} type="text" ref={inputRef} />
  );
};

// App renders a list of items
const App = ({ items }) => (
  <div style={{width: 200, height: 190, display: "flex", flexDirection: "column", justifyContent: "space-between"}}>
  {items.map(item => (
    <Item key={item.id} {...item} />
  ))}
  </div>
);
const items = [{ id: 1 }, { id: 2 }, { id: 3, selected: true }, { id: 4 }];
ReactDOM.render(
  <App items={items} />,
  root
);
.active {
  outline: 1px solid red;
}
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></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

Converting a React component to Next.JS: A step-by-step guide

I came across this React dropdown menu example and found it to be straightforward and effective. import React, { Fragment } from "react"; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from "reactstrap"; export default ...

Move the cursor to the bottom of a div that can be edited

I have been struggling to position the cursor at the end of the next or previous editable content tag if the current one is empty. However, when I try to set focus, it always ends up at the beginning of the text instead of the end. I've tried various ...

Unable to expand or collapse rows in ng-table

Looking to implement an expand and collapse feature for ng-table, where clicking on a row should expand it to show more detail. However, currently all rows expand on click. Any ideas on how to achieve this? Any assistance would be greatly appreciated, tha ...

Issue: A React component went into suspension during the rendering process, however, no alternative UI was designated

I'm currently experimenting with the code found at https://github.com/adarshpastakia/ant-extensions/tree/master/modules/searchbar Although I followed the tutorial instructions, I encountered an error. Could it be that the library is malfunctioning? I ...

PHP form does not seem to be vulnerable to cross-site scripting attacks

On one of my web pages, I have a form with an action php page using the following html syntax: <form name="form" action="test.php" method="get"> I decided to make it more secure by modifying it to: <form name="form" action="<?php echo htmlsp ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Challenges Encountered When Inputting Year in ReactJS Date Picker Component

I've encountered a problem with a date input component in my ReactJS project and need some assistance with resolving two issues: Problem 1: Year Input Length The first issue is that the year input field allows six digits, but I want to restrict it to ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

I am experiencing issues with CSS functionality in my Ruby on Rails application

Currently, I am in the process of creating a blog based on Mackenzie Child's 12 in 12 RoR tutorials. I diligently followed all the steps in the tutorial and adhered strictly to his code. However, I encountered an issue with the CSS stylesheets not be ...

Exploring the New Features of React Router Dom Version 6: Embr

In my previous code using React Router Dom v5, I was able to successfully implement nested elements. The V5 code looked like this: const App = () => { return ( <Router> <Switch> <Route exact path="/" /> {use ...

Navigating the intricacies of the "classes" property within React MaterialUI can be a source of perplexity for

Currently, I am delving into React and MUI. Recently, I attempted to follow a tutorial provided here in order to construct a sidebar using the specified steps. However, the guide utilizes makeStyles, which is incompatible with React18. In an effort to work ...

The img-fluid class is not properly adjusting the height of the image

I'm currently working with Bootstrap 4 and facing a challenge with creating a grid of 4 images - 2 on top and 2 at the bottom. I've applied the img-fluid class, but the image resizing is based solely on width, leading to the height being too larg ...

Is there a way to create a dynamic CSS for a custom JSF component through code generation?

I am currently developing a custom JSF component that displays content in multiple columns in a "responsive" manner. This component utilizes the "CSS Multi-column Layout Module" (http://www.w3.org/TR/css3-multicol/) (tutorial available in French: ). Belo ...

Angular2 material dropdown menu

Currently, I am studying angular2 with its material design. One of the modules I am using is md-select for material and here is a snippet of my code: <md-select> <md-option value="1">1</md-option> <md-option value="2">2< ...

Tips on expanding the dimensions and incorporating more members in a radar graph's Chartjs tag

I need to make some adjustments to the font size and color in a radar chart. Specifically, I want to change the name on the side of each data point. I have already tried adjusting the legend labels using the following code: options={{ ...

Struggling to retrieve the dynamic select list information from HTML and pass it to PHP. Any suggestions or guidance would be greatly

<form method="POST" name="mailform" action="sendmail.php"> <fieldset> <?php require_once("mysql_connect.php"); $sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORD ...

Execute asynchronous code in a Next.js component without relying on the UseEffect hook

Within my nextjs application, there is a StrapiImage component that takes in an image object from the strapi backend api as a prop. This component sets the width, height, URL, and any additional props for the image. Essentially, it serves as a shortcut for ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Ways to modify React icons upon clicking them?

Dealing with some icons from react-icons that seem to be causing trouble. Whenever I try to change an icon from outline to filled upon clicking, all the icons end up changing together. It's not functioning as expected. Take a look at my code snippet ...

Avoid placing content before a link to ensure better focus

I came across some CSS code that closely resembles the following code. (I copied it from http://jsfiddle.net/LmvgM/8/ thanks @thirtydot). I noticed that when the link is focused, the :before content is included. Is there a way to remove it from the highli ...