Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended.

↓ The current implementation is not effective and needs improvement

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  function handleKeyPress(e) {
    if (e.key === "e" && window.location.pathname === '/PlayMode') {
      console.log('e pressed');
      setMyHTML([<div><h1>lol</h1></div>]);
    }
  }
  
  if (!document.eventListenerAdded) {
    document.addEventListener("keyup", handleKeyPress);
    document.eventListenerAdded = true;
  }

  return (
    <div>
      {myHTML}
    </div>
  );
};

Despite the fact that putting it in a timeout resolves the issue temporarily, I believe there must be a better solution.

↓ There must be an improved approach without relying on timeouts

import React, { useState, useEffect } from 'react';

const List = ({ items }) => {

  const [myHTML, setMyHTML] = useState([]);

  console.log('starting');
  let myTimeout = setTimeout(() => {
    setMyHTML([<div><h1>pok</h1></div>]);
  }, 2000);
  
  return (
    <div>
      {myHTML}
    </div>
  );
  
};

I am determined to find an alternative solution without resorting to timeouts with minimal delay. Is there a better way to achieve this?

Answer №1

more efficient solution and recommended by the React community

function ToggleElementOnKeyPress() {
    const [toggleHtml, setToggleHtml] = useState(false);

    function handleKeyPressEvent() {
        setToggleHtml(!toggleHtml);
        console.log("You pressed a key.");
    }

    return (       
            <div onKeyDown={() => handleKeyPressEvent()} >
            {toggleHtml && <div><h1>lol</h1></div>}  
            </div>

    )
}

For more information, visit https://reactjs.org/docs/events.html#keyboard-events

Answer №2

If you want it to work, you can utilize the useEffect hook.

    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

The complete code snippet is as follows:

const List = ({ items }) => {
    const [myHTML, setMyHTML] = useState([])

    function handleKeyPress(e) {
        if (e.key === 'e' && window.location.pathname === '/PlayMode') {
            console.log('e pressed')
            setMyHTML([
                <div>
                    <h1>lol</h1>
                </div>,
            ])
        }
    }
    useEffect(() => {
        setMyHTML([
            <div>
                <h1>lol</h1>
            </div>,
        ])
    }, [])

    return <div>{myHTML}</div>
}

You can include your conditional statements (if else) within this structure.

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

Exploring the discrepancies in utilizing the i18n library versus directly incorporating locale from JSON in vue.js

Recently, I decided to incorporate Chinese language into my Vue app. To achieve this, I loaded the entire JSON text into Vuex and utilized the stored text directly, instead of relying on an i18n library. I'm curious to know if there are any potential ...

Convert HTML code into a customized JSON structure

Is there a way to convert HTML into a specific JSON object? For instance This HTML page is well-structured (originally in markdown). I am interested in creating a JSON version of the different sections present on the page. In this scenario, every "h2" s ...

useEffect invoked repeatedly

I've come across this reactjs code: import React, { useState, useEffect } from 'react' const Test = () => { const [counter, setCounter] = useState(0) useEffect(() => { const data = localStorage.getItem('counter&a ...

When using the setTimeout function to update the state, React useContext appears to be ineffective

As a newcomer to React, I have a question about refreshing the score in my card game within a forEach loop using setTimeout. While the state appears to update correctly, the DOM (Component overarching) does not reflect these changes. export function Refill ...

The function correctly identifies the image source without error

I possess a pair of images: <img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300"> <img src="images.jpg" id="img2"> Next up is some JavaScript: function validateImages () { if (document.getElementById('img2&ap ...

Accessing the facebox feature within a dropdown menu

Looking for assistance in creating a function to open a facebox when an option from a drop down list is selected. Here is what I have so far: <select><option value="www.google.com/" id="xxx"></option></select> In the header sectio ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Troubleshooting Next.js deployment with Nginx: experiencing a 403 forbidden error with chunk script files

After deploying my Next app using Nginx, I encountered an issue where the js files inside the _next/static/chunks directory were getting a 403 forbidden error. https://i.stack.imgur.com/TB9TX.png Interestingly, only the js files in the chunks directory w ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

What are some strategies for stopping Knex.js from executing a query object upon return from an asynchronous function?

My node.js backend utilizes Knex.js to construct dynamic DB queries based on various inputs. The challenge I'm facing is handling asynchronous processing of certain inputs. When returning a knex query object from an async function or a Promise resolve ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

How to position text in the center of a video using CSS

My attempt to center the name of my blog on top of a video background was not successful, even though I tried positioning it absolutely with 50% from the top. Can someone assist me in vertically and horizontally centering the text over the video? Here is ...

Asynchronously loading images within a div that has overflow: scroll, as they come into view

The setup I have for displaying my content looks like this: <div id="content" style="overflow:scroll;height:500px; width: 500px;"> <div style="width:500px;height:100px;> <img src='http://graph.facebook.com/user1/picture?width= ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

What could be causing the Gruntfile to throw an error?

Getting an unexpected error while trying to run grunt $ grunt Loading "Gruntfile.js" tasks...ERROR >> SyntaxError: Unexpected token : Warning: Task "default" not found. Use --force to continue. Execution terminated due to warnings. Here is my ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Container that displays vertical scroll while permitting floating overflows

Is there a way to set up a container so that when the window size is too small, it displays a scroll bar to view all elements that don't fit in one go? At the same time, can the child containing floating elements be allowed to extend beyond the bounda ...

Mastering CSS: Optimizing Div Placement Across Sections

I am currently working on developing a sleek and modern landing page with multiple sections, each designed to catch the eye. This style is all the rage at the moment, featuring large headers, ample padding, bold text, and a visually appealing divider betwe ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

Showcasing articles in an XML feed according to specific keywords found in the headline

I'm currently working on designing a website for a client and I want to minimize my involvement in its maintenance. I am considering using RSS feeds to automate the process by having content posted on Blogger and then feeding it to the site. However, ...