What is the best approach to bring a button into focus after it has been enabled in a React.js application

I'm a beginner in react js and I'm attempting to set the focus on a button after filling out all input fields. However, despite programmatically enabling the button with autoFocus implemented, I am unable to focus on it.

return (
            <div style={{ marginTop: '10%', marginLeft: '25%', backgroundImage: 'linear-gradient(to right, rgba(153,102,255,1), rgba(153,102,255,0.5))', color: '#f3f5f7', height: 'fit-content%', width: '50%', paddingBlockStart: '50px', position: 'fixed' }}>

                <form align="center"  >
                    <h1 align="center"> Login</h1><br /><br />

                    <Grid container direction="row" justify="center" alignItems="center" spacing={4} >
                        <Grid item >
                            <TextField input type="number" placeholder={this.props.intl.formatMessage(messages.PlaceHolder)} id="mobileNo" variant="outlined" size="small" required style={{ backgroundColor: 'white', width: '300px', borderRadius: '5px', border: '1px solid' }} onInput={(e) => { e.target.value = Math.max(0, parseInt(e.target.value)).toString().slice(0, 11) }} />
                        </Grid>
                        <Grid item >
                            <MyButton disabled={this.state.validate} variant="outlined" color="primary" onClick={() => this.clickValidate()}> {this.props.intl.formatMessage(messages.ValidateButton)} </MyButton>
                            <ToastContainer />
                        </Grid>
                    </Grid>
                    <br /><br />
                    <Grid container direction="row" justify="center" alignItems="center" spacing={4} >
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_1" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_2" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_3" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_4" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_5" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                        <Grid item >
                            <ValidationTextField type="number" onInput={this.restrictAlphabets} min={0} required id="otp_6" variant="outlined" size="small" onChange={this.handleChange} inputProps={{ maxLength: 1, size: 1 }} style={{ backgroundColor: 'white', width: '50px', borderRadius: '5px', border: '1px solid' }} />
                        </Grid>
                    </Grid>

                    <br /><br /><br />

                    <MyButton id="login" variant="outlined" aria-disabled={this.state.login} color="primary" onClick={this.handelLogin}> {this.props.intl.formatMessage(messages.Login)} </MyButton>
                    <br /><br /><br />
                    <Link style={{ color: 'white' }} onClick={this.handelResendOtp}> {this.props.intl.formatMessage(messages.ResendOtp)} </Link>
                    <br /><br /><br />

                </form>

                <div id="regAlert" style={this.state.unregistered ? {} : { display: 'none' }}>
                    <Alert severity="info"><h3>You are not registered with us, kindly visit www.agoraservices.us for registration!</h3></Alert >
                </div>

            </div>

Above you can find some example code where I'm trying to set the focus on the Login button

Answer №1

Utilize the Ref feature provided by React to easily reference any HTML element, then access it through its current property.

Check out this example on CodeSandbox

function App() {
  const mybtnRef = useRef();
  React.useEffect(() => {
    mybtnRef.current.focus();
  }, []);
  return (
    <div className="App">
      <button ref={mybtnRef} onClick={()=>console.log("hello")}>Click here</button>
    </div>
  );
}

Answer №2

<!-- This code includes a reference for focusing and changing background color as well-->
<html>

<head>
  
    <style>
        td {
            border: 1px solid #ddd;
            padding: 10px;
        }
        
        td:first-child {
            width: 300px;
        }
    </style>  
</head>

<body>
  
  <div id="message">some text here</div>
   
 <div>
        <input type="text" id="addFriend">
        <input type="button" id="addNew" value="Add Friend"> </div>
    <div class="output"></div>
    <script>
<!-- array function to list out -->
        var myArray = ["Laurence", "Mike", "John", "Larry", "Kim", "Joanne", "Lisa", "Janet", "Jane"];
        window.onload = build;
        document.getElementById('addNew').addEventListener('click', addN, false);

        function addN() {
            var a = document.getElementById('addFriend').value;
            myArray.push(a);
            build();
        }

        function build() {
            var html = "<h1>Click Table</h1><table>";
            for (var x = 0; x < myArray.length; x++) {
                html += '<tr id="id' + x + '" data-row="' + x + '"><td>' + myArray[x] + '</td><td><a href="#" data-action="delete">Del</a></td><td><a href="#" data-action="edit">Edit</a></td></tr>';
            }
            document.querySelector('.output').innerHTML = html;
            var dad = document.querySelectorAll('[data-action="delete"]');
            for (var x = 0; x < dad.length; x++) {
                dad[x].addEventListener('click', function () {
                    event.preventDefault();
                    var iValue = this.closest('[data-row]').getAttribute('data-row');
                    var r = myArray.splice(iValue, 1);
                    build();
                    console.log(r);
                })
            }
            var dae = document.querySelectorAll('[data-action="edit"]');
            for (var x = 0; x < dae.length; x++) {
                dae[x].addEventListener('click', function () {
                    event.preventDefault();
                    var row = this.closest('[data-row]');
                    var rid = row.getAttribute('data-row');
                    row.style.backgroundColor = "Yellow";
                    var td = row.firstElementChild;
                    var input = document.createElement('input');
                    input.type = "text";
                    input.value = td.innerText;
                    td.innerHTML = "";
                    td.appendChild(input);
                    input.focus();
                    input.onblur = function () {
                        td.removeChild(input);
                        td.innerHTML = input.value;
                        myArray[rid] = input.value;
                        row.style.backgroundColor = "White"
                    }
                })
            }
            console.log(dad);
        }
    </script> 
</body>

</html>

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

Communicating between parent and child components in React within an Asp.net Core 2.0 environment

I am encountering an issue with my React app (not ReactJs) in asp.net core 2.0. The problem lies in the communication between a child component and its parent. Specifically, I need to relay information to the parent when a button in the child component is ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Passing a variable to the render method in a PDF document

I'm currently working on a project with Django where I need to convert an HTML monthly report into a PDF. The data for the report is retrieved from a database based on the selected month. I am facing an issue in sending the selected month from the HTM ...

Iterate through an array and update the innerHTML content for each value contained in the array

Looking to replace a specific word that keeps appearing on my website, I experimented with various functions and stumbled upon this method that seems to work: document.getElementsByClassName("label")[0].innerHTML = document.getElementsByClassName ...

Accessing the clandestine div via direct hyperlink

I have incorporated a toggle plugin from this website to display hidden divs. Each hidden div is identified by a unique id. Is there a method to show a specific div using a direct link? For instance, by entering domain.com/page.php#HiddenDiv2, it should ...

Ways to determine the overall cost of a shopping cart using Vuejs Vuex

Running a business requires managing various aspects, including tracking the inventory. In my store, I have an array called basketContents that contains items with their respective quantities and prices. An example of how it looks is: state: { basketConte ...

LESS — transforming data URIs with a painting mixin

Trying to create a custom mixin for underlining text, similar to a polyfill for CSS3 text-decoration properties (line, style, color) that are not yet supported by browsers. The idea is to draw the proper line on a canvas, convert it to a data-uri, and the ...

Error: The script is not found in the package.json configuration

I encountered the following error while trying to execute npm run dev: Error: Missing script: "dev" Error: Error: To view a list of available scripts, use the command: Error: npm run Here is a list of scripts present in my package.json file: "scripts ...

Troubleshooting problems with dropdown binding in Knockout ObservableArray

I am encountering an issue with fetching data from a restful wcf service during page load and binding it to a dropdown, which is not functioning as expected. function CreateItem(name, value) { var self = this; self.itemNam ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

"Automatically close the fancybox once the form is confirmed in the AJAX success

Having an issue with closing my fancybox after submitting the registration form on my website. I am using the CMS Pro system.... Here is how I display the fancybox with the form: submitHandler: function(form) { var str = $("#subscriber_application"). ...

"Exploring the Method of Inheriting from a BaseComponent in Angular 2

I’ve been working on an Angular project and I’m looking to streamline the creation of components with shared functionality. For example, let’s say I have a TeacherIndexComponent: @Component({ selector: 'app-teacher-index', templateUrl: ...

Experience the power of Meteor Accounts-facebook in React instead of BlazeJS!

I'm curious if there is a method to implement a Facebook login/sign up process with the meteor accounts library, utilizing ReactJS instead of BlazeJS. Most of the examples I've come across online are designed for BlazeJS and involve an HTML file ...

Using jQuery to animate two images simultaneously in opposite directions

Trying to make two images animate using a single function. The issue is that one image needs to animate the left attribute while the other needs to animate the right. Here's what I have so far: $(document).ready(function(){ v ...

Verifying assigned role and running a specified task

I have a task to verify if a user possesses a specific role, and if they do, to remove it. If the user does not have the role, then display a certain message. let user = message.guild.member(message.mentions.users.first() || message.guild.members.get(args ...

The minified version of Bootstrap's CSS will only be loaded when I explicitly import it in my index

I used to rely on BootstrapCDN for my styles, but now I want to download the files and use them locally. However, when I try to load the styles without an internet connection, they don't seem to work properly, especially the grid layout. My current s ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

Covering the full width of the page, the background image

My struggle is with setting a background image to 100% width, as the image ends up getting cut off on half of the screen. The picture becomes wider than my display area. How can I resolve this issue so that the image width adjusts to fit the screen without ...

Retrieve the ID from the database and showcase the content on a separate page

My database has a table named "apartments," and I am using the following code to display its contents on a single page: $connect = mysqli_connect("localhost","root","","db_dice"); $query = "SELECT * FROM apartment ORDER BY ID DESC"; $records = mysqli_quer ...

Angular 2 dropdown list that allows users to add a personalized value in the HTML code

Here is the scenario I am dealing with We are displaying a fixed dropdown list to the user For example, a dropdown list has 4 options such as apple, orange, grape, pineapple and 'create your own' If the user is not satisfied with the provided ...